Shallow Copy VS Deep Copy

 Posted by Bh80prk on 12/21/2012 | Category: C# Interview questions | Views: 2673 | Points: 40

Shallow copy

Copies the structure of the object

The easiest way to think of it is a shallow copy allows you to replicate the array once... it then ignores the relationship it has with the original array.

OriginalArray = ShallowArray.Clone();
The MemberwiseClone method creates a shallow copy by 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

For example, consider an object called X that references objects A and B. Object B, in turn, references object C. A shallow copy of X creates new object X2 that also references objects A and B.

Deep copy

Copies structure as well as data.

The deep copy will be persistent and any changes you make to the original array will be reflected in both copies.

OriginalArray = DeepArray;

In contrast, a deep copy of X creates a new object X2 that references the new objects A2 and B2, which are copies of A and B. B2, in turn, references the new object C2, which is a copy of C. The example illustrates the difference between a shallow and a deep copy operation.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response