![]() |
|||
Difference between Shallow Copy and Deep Copy in .NET
By: rekha singh | 23 Jan 2010 1:03 pm
Hi, What is the Difference between Shallow Copy and Deep Copy by the use of C# language. Thanks. CommentsShallow Copy: 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 --> 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 are clsShallow class to be cloned which include value types (like Age) and ref types (like EmpSalary is a class) public class clsShallow
now, let us debug and trace the outputs to do the shallow copy by the use of CreateShallowCopy() method first, use the following code to call the CreateShallowCopy method from other classes // Creates an instance of clsShallow and assign values to its fields. After assigning the values (value and ref types ones) to the object objShallow and before doing the shallow copy
the values are : (for the new created object)
By: rekha singh | 23 Jan 2010
Deep Copy: If a field is a value type --> a bit-by-bit copy of the field is performed Note: the classes to be cloned must be flagged as [Serializable] Example: the following are clsDeep class to be cloned which include value types (like Age) and ref types (like EmpSalary is a class) [Serializable]
now, let us debug and trace the outputs to do the deep copy by the use of CreateDeepCopy() method first, use the following code to call the CreateDeepCopy method from other classes // Creates an instance of clsDeep and assign values to its fields.
After assigning the values (value and ref types ones) to the object objDeep and before doing the deep copy the values are : (for the current object value)
then do the deep copy and modify the value of clsref.salary ,reference field type, then check the values of m2 , new created object. (ref and value fields) again
By: rekha singh | 23 Jan 2010
|




