Shallow Copy
- Shallow copy creates new object
- Then copy all non static fields to the new object
- System.Object.MemberwiseClone() method creates shallow copy of object
Deep Copy
- Deep copy creates new object
- Then copy all feilds to the new object
- Deep copy of an object can be created using Serialization
- Mark the target class as [Serializable]
References:
- MemberWiseClone - (shallow copy)
Scenario: (C#.NET) There is an Employee class, which has 2 properties, ID & Name. There is an Employee class object E1. I want to create Shallow copy to E2 & Deep copy to E3. How?
[Serializable]
public class Employee : ICloneable
{
private int id;
private string name;
public int ID
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public Employee ShallowCopy()
{
//shallow copy
return (Employee)this.MemberwiseClone();
}
#region ICloneable Members
public object Clone()
{
//deep copy
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
object obj = bf.Deserialize(ms);
ms.Close();
return obj;
}
#endregion
}
class DeepShallowSample
{
public DeepShallowSample()
{
Employee e1 = new Employee();
e1.ID = 162;
e1.Name = "Nidhish";
Console.WriteLine(e1.GetHashCode());
//Shallow copy
Employee e2 = e1.ShallowCopy();
Console.WriteLine(e2.GetHashCode());
//Deep copy
Employee e3 = (Employee)e1.Clone();
Console.WriteLine(e3.GetHashCode());
}
}