Thursday 28 November 2013

Shallow Copy vs. Deep Copy in .NET

 

 

Shallow Copy

Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed; for a reference type --> the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

 

In C# and VB.NET, shallow copy is done by the object method MemberwiseClone().

Example: the following clsShallow class is to be cloned which includes value types (like Age) and ref types (like EmpSalary is a class):

 

image

 

 

image

 

The values are (for the newly created object): Age: 25 (value type), a new copy of the objShallow object; EmpSalry: has a salary value of 2000 (ref type), a reference to objShallow.EmpSalry object, which is also referenced to the clsref object.

Note: values of m2.EmpSalry and clsref are the same after modifying the clsref values (reference type concept).

 

 

Deep Copy

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed. If a field is a reference type --> a new copy of the referred object is performed.

Note: the classes to be cloned must be flagged as [Serializable].

Example: the following is the clsDeep class to be cloned which includes value types (like Age) and ref types (like EmpSalary which is a class).

 

image

 

 

image

 

 

image

 

image

 

 

 

 

 

 

 

 

Blogger Labels: Copy,Deep,reference,method,Example,EmpSalary,EmpSalry,salary,Note,concept,Serializable,clsref

No comments:

Post a Comment