Monday, July 7, 2008

Generic implementation of Deep and Shallow Copy

A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. But the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory.

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields.

In this article I will show how to create a generic implementation of Shallow copy and deep copy in C#.

Step 1: Creating the Abstract class


public abstract class IDeepShallowCopy


//Shallow Copy implementation

public T ShallowCopy()


return (T)this.MemberwiseClone();


//Deep Copy implementation

public T DeepCopy()


MemoryStream memoryStream = new MemoryStream();

BinaryFormatter binaryFormatter = new BinaryFormatter();

binaryFormatter.Serialize(memoryStream, this);

memoryStream.Seek(0, SeekOrigin.Begin);

T objectCopy = (T)binaryFormatter.Deserialize(memoryStream);


return objectCopy;



Step 2: Inherit from the abstract class


public class Employee : IDeepShallowCopy<Employee>


public String name { get; set; }

public Int32 age { get; set; }


Now you can use the Deep Copy and Shallow copy feature for the Employee Class like

Employee deepEmployee = e.DeepCopy();

Employee shallowEmployee = e.ShallowCopy();

No comments: