How do you do a deep copy of an object in .NET?

CsharpServer Side ProgrammingProgramming

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated

Deep Copy is used to make a complete deep copy of the internal reference types.

In another words a deep copy occurs when an object is copied along with the objects to which it refers

Example

 Live Demo

class DeepCopy {
   public int a = 10;
}
class Program {
   static void Main() {
      //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();
   }
}

Output

10 10
5 10
raja
Published on 08-Aug-2020 12:13:21
Advertisements