Shallow Copy

Why Trust Techopedia

What Does Shallow Copy Mean?

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.

Advertisements

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.

Techopedia Explains Shallow 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.

The methods to perform shallow copy include:

  • Call the MemberwiseClone method of the object
  • Create a clone manually through a custom method that is tedious but easy to control
  • Use a reflection technique that provides automated facility to perform shallow copy, but with performance overhead
  • Use a serialization method that is slower than reflection but automated and simple

Shallow copy cannot be used where the object has members of reference type that are modified frequently.

Advertisements

Related Terms

Margaret Rouse
Technology expert
Margaret Rouse
Technology expert

Margaret is an award-winning writer and educator known for her ability to explain complex technical topics to a non-technical business audience. Over the past twenty years, her IT definitions have been published by Que in an encyclopedia of technology terms and cited in articles in the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine, and Discovery Magazine. She joined Techopedia in 2011. Margaret’s idea of ​​a fun day is to help IT and business professionals to learn to speak each other’s highly specialized languages.