Shallow copying an object in C#

C# supports two basic types of object copying:

  • Shallow copying
  • Deep copying

Let’s have a look at how shallow copying can be done in C#.

Shallow Copying

In the case of shallow copying, a copy of the references/addresses is made. Therefore, the addresses of the original and the copied object will be the same because they will point to the same memory location.

svg viewer

Code

Let’s create the class Person, which will have the attributes name, ID, ​and age. The ID attribute will hold a PersonID class object. This class will also include a ShallowCopy method to create a shallow copy of the object. The built-in C# class function this.MemberwiseClone() will create a shallow copy of the current System.Object. See the code below:

class ShallowCopyDemo {
static void Main(string[] args)
{
Person p1 = new Person();
p1.name = "Hassan";
p1.age = 22;
p1.ID = new PersonID(3343);
// Calling ShallowCopy() method
Person p2 = p1.ShallowCopy();
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 = 4544;
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 ShallowCopy()
{
return (Person) this.MemberwiseClone();
}
}

The Person.ID property returns a PersonID object. When a Person object is cloned through the MemberwiseClone method, the cloned Person object becomes an independent copy, but both objects still share the same Person.ID object reference.

Therefore, modifying the clone’s Person.ID attribute also changes the original object’s Person.ID attribute.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved