Deep copying an object in C#

To make a deep copy of an object is to clone it. When we use the = operator, we are not cloning an object; instead, we are referencing our variable to the same object (i.e., shallow copy).

In other words, changing one variable’s value affects the other variable’s value because they are referring (or pointing) to the same object. This is not the case with a deep copy; the difference between a shallow and a deep copy is that modifying a deep copy’s object’s values does not modify the original object (unlike in shallow copying).

svg viewer

Code

Let’s create the class Person, which will have name, ID, and age attributes. T​he ID attribute will hold a PersonID class object. This class will also include a DeepCopy method that will return a deep copy of the object. See the code below:

class DeepCopyDemo {
static void Main(string[] args)
{
Person p1 = new Person();
p1.name = "Hassan";
p1.age = 22;
p1.ID = new PersonID(3343);
// Calling DeepCopy() method
Person p2 = p1.DeepCopy();
System.Console.WriteLine("Before Changing: ");
// Value of attributes of c1 and c2 before changing
// the values
System.Console.WriteLine("p1 instance values: ");
System.Console.WriteLine(" Name: {0:s}, Age: {1:d}", p1.name, p1.age);
System.Console.WriteLine(" Value: {0:d}", p1.ID.IDNumber);
System.Console.WriteLine("p2 instance values:");
System.Console.WriteLine(" Name: {0:s}, Age: {1:d}", p2.name, p2.age);
System.Console.WriteLine(" Value: {0:d}", p2.ID.IDNumber);
// Modifying attributes of p1
p1.name = "Hamza";
p1.age = 20;
p1.ID.IDNumber = 4344;
System.Console.WriteLine("\nAfter Changing attributes of p1: ");
// Value of attributes of c1 and c2 after changing
// the values
System.Console.WriteLine("p1 instance values: ");
System.Console.WriteLine(" Name: {0:s}, Age: {1:d}", p1.name, p1.age);
System.Console.WriteLine(" Value: {0:d}", p1.ID.IDNumber);
System.Console.WriteLine("p2 instance values:");
System.Console.WriteLine(" Name: {0:s}, Age: {1:d}", p2.name, p2.age);
System.Console.WriteLine(" Value: {0:d}", p2.ID.IDNumber);
}
};
public class PersonID
{
public int IDNumber;
public PersonID(int id)
{
this.IDNumber = id;
}
}
public class Person
{
public int age;
public string name;
public PersonID ID;
public Person DeepCopy()
{
Person temp = (Person) this.MemberwiseClone();
temp.ID = new PersonID(this.ID.IDNumber);
temp.name = this.name;
return temp;
}
}

this.MemberwiseClone() will create a shallow copy of the p1 object. However, to convert this clone (p2) into a deep copy, the ID attribute will have to be assigned a new PersonID object, and the newly allocated object will have a different reference than that of ​p1.ID. This means that changing p2.ID will not change p1.ID, ​as can be seen in the output.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved