What is Shallow Copy and how it is different from Deep Copy in C#?

CsharpServer Side ProgrammingProgramming

Shallow Copy

A shallow copy of an object copies the "main" object, but doesn’t copy the inner objects.

The "inner objects" are shared between the original object and its copy.

The problem with the shallow copy is that the two objects are not independent. If you modify the one object, the change will be reflected in the other object.

Deep Copy

A deep copy is a fully independent copy of an object. If we copied our object, we would copy the entire object structure.

If you modify the one object, the change will not be reflected in the other object.

Example

class Program{
   static void Main(string[] args){
      //Shallow Copy
      ShallowCopy obj = new ShallowCopy();
      obj.a = 10;
      ShallowCopy obj1 = new ShallowCopy();
      obj1 = obj;
      Console.WriteLine("{0} {1}", obj1.a, obj.a); // 10,10
      obj1.a = 5;
      Console.WriteLine("{0} {1}", obj1.a, obj.a); //5,5
      //Deep Copy
      DeepCopy d = new DeepCopy();
      d.a = 10;
      DeepCopy d1 = new DeepCopy();
      d1.a = d.a;
      Console.WriteLine("{0} {1}", d1.a, d.a); // 10,10
      d1.a = 5;
      Console.WriteLine("{0} {1}", d1.a, d.a); //5,10
      Console.ReadLine();
   }
}
class ShallowCopy{
   public int a = 10;
}
class DeepCopy{
   public int a = 10;
}

Output

10 10
5 5
10 10
5 10
raja
Published on 19-Aug-2020 12:57:39
Advertisements