What are Shallow Copy and Deep Copy in .NET?

 Posted by Tripati_tutu on 11/2/2010 | Category: ASP.NET Interview questions | Views: 17315 | Points: 40

The terms "Shallow Copy " and "Deep Copy " which refer to the way the objects are copied, for example, during the invocation of a copy constructor or assignment operator. The deep copy can also be called as member wise copy and the copy operation respects object semantics. For example, copying an object that has a member of type standard string ensures that the corresponding standard string in the target object is copy-constructed by the copy constructor of class string.

Shallow copy: This is nothing but 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 then a bit-by-bit copy of the field is performed. If it is a reference type then the reference is copied but not the referred object. Therefore, the original object and its clone refer to the same object.

Deep copy: Deep copy is partially same as shallow copy, but the difference is deep copy copies the whole object and makes a different object, it means it do not refer to the original object while in case of shallow copy the target object always refer to the original object and changes in target object also make changes in original object. It serializes the objects and deserializes the output.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response