What Does Deep Copy Mean?
Deep copy, in C#, refers to a technique by which a copy of an object is created such that it contains copies of both instance members and the objects pointed to by reference members.
Deep copy is intended to copy all the elements of an object, which include directly referenced elements (of value type) and the indirectly referenced elements of a reference type that holds a reference (pointer) to a memory location that contains data rather than containing the data itself. Deep copy is used in scenarios where a new copy (clone) is created without any reference to original data.
Techopedia Explains Deep Copy
Deep copy differs from shallow copy in the manner in which the reference type members of the object are copied. While copying the field members of value type in both cases, a bit-by-bit copy of field is performed. When copying fields of reference type, shallow copy involves copying only the reference, whereas in deep copy, a new copy of the referred object is performed.
Deep copy can be illustrated with an example by considering an Employee object having AddressInfo as a member of reference type along with other members of value type. A deep copy of Employee creates a new object, Employee2, with members of value type equal to Employee but references a new object, AddressInfo2 , which is a copy of AddressInfo.
Deep copy can be implemented using any of the following methods:
- Copy constructor of the class can be implemented with the necessary logic for copying members of both value and reference (after proper memory allocation) types. This method is tedious and error-prone.
- System.Object.MemberwiseClone method can be used to copy the nonstatic members of value type. Copies of objects of reference type can be created and assigned with the same set of values as the original
- An object that has to be deep copied can be serialized and de-serialized it into a new object by restoring it. This method is automated and does not require code changes for modifications in object members but is slower than other methods and requires the cloned object to be serializable
- Reflection with recursion can be used to get a shallow copy, at which point the additional code necessary for deep copy can be added. This method is automated and does not require code changes for any addition or removal of fields in the object. It is slower and not allowed in partial trust environment
- Intermediate language code can be used, which is faster but results in lesser code readability and difficult maintenance
To implement deep copy:
- The object has to be well-defined and cannot be arbitrary
- Properties of object will not be considered
- Cloning has to be automated with intelligence for special cases (like objects containing unmanaged references)