Object Cloning

Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type, then bit-by-bit copy of the field is performed. For a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

What it means is that instead of creating new objects, shallow copy scenario shares a single reference. So, changing value via one reference will impact the value represented by the other reference.

MemberwiseClone 

This object creates shallow copy by creating a new object.

Shallow copy code and explanation 

  1. public class Human  
  2. {  
  3.     public int Age;  
  4.     public string Name;  
  5.     public IdInfo IdInfo;  
  6.    
  7.     public Human ShallowCopy()    {  
  8.          return (Human)this.MemberwiseClone();  
  9.     }  
  10. }  
  11. public class Example  
  12. {  
  13.     public static void Main()  
  14.     {  
  15.         Human p1 = new Human();  
  16.         p1.Age = 20;  
  17.         p1.Name = "t1";  
  18.         p1.IdInfo = new IdInfo(100);       
  19.         Human p2 = p1.ShallowCopy();  
  20.         // Display values of p1, p2  
  21.         Console.WriteLine("Original values of p1 and p2:");  
  22.         Console.WriteLine("   p1 instance values: ");  
  23.         DisplayValues(p1);  
  24.         Console.WriteLine("   p2 instance values:");  
  25.         DisplayValues(p2);         
  26.         p1.Age = 30;  
  27.         p1.Name = "t2";  
  28.         p1.IdInfo.IdNumber = 200;  
  29.         Console.WriteLine("\nValues of p1 and p2 after changes to p1:");  
  30.         Console.WriteLine("   p1 instance values: ");  
  31.         DisplayValues(p1);  
  32.         Console.WriteLine("   p2 instance values:");  
  33.         DisplayValues(p2);  
  34.         Console.ReadLine();  
  35.     }  
  36.     public static void DisplayValues(Human p)  
  37.     {  
  38.         Console.WriteLine("      Name: {0:s}, Age: {1:d}", p.Name, p.Age);  
  39.         Console.WriteLine("      Value: {0:d}", p.IdInfo.IdNumber);        
  40.     }  
  41. }  

Explanation


Deep Copy

Deep copies duplicate everything. Two different objects get created with shared reference. It means, in deep copy, object is copied along with the objects to which it refers.

There are multiple ways to perform "Deep Copy".

Some are discussed below.

  • Use copy constructor and create new object.
  • You can call MemberwiseClone method and create a shallow copy of an object, and then assign new objects whose values are reference types.
  • You can serialize object and then de-Serialize the object to different object variable.
  • You can do serialization of data and then deserialize the data to new object.
  • Use reflection with recursion.

Code and explanation

  1. using System;  
  2.    
  3. public class IdInfo  
  4. {  
  5.     public int IdNumber;  
  6.    
  7.     public IdInfo(int IdNumber)  
  8.     {  
  9.         this.IdNumber = IdNumber;  
  10.     }  
  11. }  
  12.    
  13. public class Human  
  14. {  
  15.     public int Age;  
  16.     public string Name;  
  17.     public IdInfo IdInfo;  
  18.    
  19.     public Human DeepCopy()  
  20.     {  
  21.         Human other = (Human)this.MemberwiseClone();  
  22.         other.IdInfo = new IdInfo(IdInfo.IdNumber);  
  23.         other.Name = String.Copy(Name);  
  24.         return other;  
  25.     }  
  26. }  
  27.    
  28. public class Example  
  29. {  
  30.     public static void Main()  
  31.     {          
  32.         Human p1 = new Human();  
  33.         p1.Age = 20;  
  34.         p1.Name = "t1";  
  35.         p1.IdInfo = new IdInfo(100);         
  36.         Human p3 = p1.DeepCopy();         
  37.         p1.Name = "t2";  
  38.         p1.Age = 30;  
  39.         p1.IdInfo.IdNumber = 200;  
  40.         Console.WriteLine("\nValues of p1 and p3 after changes to p1:");  
  41.         Console.WriteLine("   p1 instance values: ");  
  42.         DisplayValues(p1);  
  43.         Console.WriteLine("   p3 instance values:");  
  44.         DisplayValues(p3);  
  45.         Console.ReadLine();  
  46.     }  
  47.    
  48.     public static void DisplayValues(Human p)  
  49.     {  
  50.         Console.WriteLine("      Name: {0:s}, Age: {1:d}", p.Name, p.Age);  
  51.         Console.WriteLine("      Value: {0:d}", p.IdInfo.IdNumber);  
  52.     }  
  53. }  
Explanation 

An Explanatory example of both (taken from StackOverflow) 
  1. class A  
  2.     {  
  3.         public int a = 0;  
  4.         public void display()  
  5.         {  
  6.             Console.WriteLine("The value of a is " + a);  
  7.         }  
  8.     }  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             A ob1 = new A();  
  14.             ob1.a = 10;  
  15.             ob1.display();  
  16.             A ob2 = new A();  
  17.             ob2 = ob1;  
  18.             ob2.display();  
  19.             Console.Read();  
  20.         }  
  21.     }  

Question-Which type of copy is this?

Answer-Shallow Copy

  1. ob1.a = 5; // <-- If you see value of ob2.a after this line, it will be 5.  
  2.    
  3. Deep Copy will be:  
  4. A ob1 = new A();  
  5.  ob1.a = 10;  
  6.  A ob2 = new A();  
  7.  ob2.a = ob1.a;  
  8.    
  9.  ob1.a = 5; // <-- If you see value of ob2.a after this line, it will be 10  
Shocking-This does not go with my diagram. Here, we equate the objects using “=” sign.

Note- Read “=” in terms of objects. Just to give heads up, using “=” ,share the reference.

Additional Notes

ICloneable interface is the key to learn object cloning.

Memberwise also uses this interface internally to do shallow copy and this same interface can be used to perform deep copy. I thought to explain but they are already explained in best possible way at the below links.

Recommended Reading,

  • http://www.informit.com/articles/article.aspx?p=25352&seqNum=3
  • http://www.windowsdevcenter.com/pub/a/dotnet/2002/11/25/copying.html?page=2
  • http://stackoverflow.com/questions/3345389/copy-constructor-versus-clone
  • http://seesharpconcepts.blogspot.com/2012/05/shallow-copy-and-deep-copy-in-c.html
  • http://www.cshandler.com/2012/07/shallow-copy-and-deep-copy-using.html#.Vdwms9zVFJs
  • https://www.agiledeveloper.com/articles/cloning072002.htm