Shallow copy, in C#, is the process of creating a clone of an object by instantiating a new instance of the same type as original object and copying the non-static members of the existing object to the clone. The members of the value type are copied bit by bit while the members of the reference type are copied such that the referred object and its clone refer to the same object.
In general, shallow copy is used when performance is one of the requirements along with the condition that the object will not be mutated throughout the application. By passing the clone containing immutable data, the possibility of corruption by any code is eliminated. Shallow copy is found to be efficient where object references allow objects to be passed around by memory address so that the entire object need not be copied.
Shallow copy is also known as memberwise copy.
Shallow copy is similar to deep copy in the assignment of each member of an object to that of another object, but it differs in the manner in which the field of reference type is copied. Unlike in shallow copy where the reference is only copied, in deep copy, a new copy of the referred object is created.
For example, consider an employee object that contains details of personal information, including a list of address objects that store multiple employee addresses. By performing a shallow copy of an employee object, a clone of the employee object can be created with references to the same list of address objects that are owned by the original employee object.
Get Techopedia delivered to your inbox!