Search This Blog

Tuesday, August 28, 2012

Difference between Shallow and Deep copy


Difference between Shallow and Deep copy:
Shallow Copy:
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Shallow Copy points to the same location in memory as Source does.
Value type:  Copy of the field is performed

Reference type: The reference is copied NOT the object so original object
and its Shallow Copy refer to the same object.



Deep Copy:
Deep copies duplicate everything structure and element both. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
Deep Copy points to a different location in memory, but the elements are the same.
Value type: Copy of the field is performed
Reference type: The object itself is copied, NOT only the reference so original object and its Deep Copy refer to two different object.


Example:
var realdata = { FName="ask", LName="dotnet" };
var shallow = ShallowCopyOf(realdata);
var deep = DeepCopyOf(realdata);
realdata.LName = ".net";
WriteLine(realdata.LName); // outputà .net
WriteLine(shallow.LName); // outputà .net
WriteLine(deep.LName); // outputà dotnet

No comments :