Hello Everyone, Hope you are doing well,
Today, in this article, we will delve into one of the core concepts of C#, which is a shallow copy or a deep copy.
When working with objects in C#, copying data often plays a critical role. Depending on the requirements, you might choose either a shallow copy or a deep copy. This article will explain these concepts with user-friendly examples and highlight their differences.
What is a Shallow Copy?
A shallow copy duplicates only the top-level structure of an object. However, it does not create independent copies of the referenced objects. Instead, both the original and copied objects share references to the same inner objects.
Shallow Copy Example
Here's a code snippet that demonstrates shallow copying in C#:
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("--- Test Shallow Copy: Started ---");
// Original object
var person1 = new Person
{
Name = "John",
Address = new Address { City = "New York" }
};
// Shallow copy
var person2_ShallowCopy = person1.ShallowCopy();
// Modify the copy
person2_ShallowCopy.Name = "Doe";
person2_ShallowCopy.Address.City = "Los Angeles";
// Display results
Console.WriteLine($"Person1: {person1.Name}, {person1.Address.City}"); // Doe, Los Angeles
Console.WriteLine($"Person2: {person2_ShallowCopy.Name}, {person2_ShallowCopy.Address.City}"); // Doe, Los Angeles
Console.WriteLine("--- Test Shallow Copy: End ---");
}
}
public class Address
{
public string City { get; set; }
}
public class Person
{
public string Name { get; set; }
public Address Address { get; set; }
public Person ShallowCopy()
{
return (Person)this.MemberwiseClone(); // Shallow Copy
}
}
Shallow Copy Output
--- Test Shallow Copy: Started ---
Person1: Doe, Los Angeles
Person2: Doe, Los Angeles
--- Test Shallow Copy: End ---
Explanation
- A Person object (person1) is created with the Name "John" and an Address object referencing "New York".
- A shallow copy (person2_ShallowCopy) is created using MemberwiseClone().
- Changes to person2_ShallowCopy.Address.The city also affects person1.Address.City because both share the same reference to the Address object.
What is a Deep Copy?
A deep copy creates a completely independent duplicate of an object, including all referenced objects. This ensures that changes made to the copied object do not affect the original object.
Deep Copy Example
Now let's look at a deep copy implementation:

Join the conversation! Your thoughts help the community grow.