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:
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("--- Test Deep Copy: Started ---");
// Original object
var person1 = new Person
{
Name = "John",
Address = new Address { City = "New York" }
};
// Deep copy
var person2_DeepCopy = person1.DeepCopy();
// Modify the copy
person2_DeepCopy.Name = "Doe";
person2_DeepCopy.Address.City = "Los Angeles";
// Display results
Console.WriteLine($"Person1: {person1.Name}, {person1.Address.City}"); // John, New York
Console.WriteLine($"Person2: {person2_DeepCopy.Name}, {person2_DeepCopy.Address.City}"); // Doe, Los Angeles
Console.WriteLine("--- Test Deep Copy: End ---");
}
}
public class Address
{
public string City { get; set; }
public Address DeepCopy()
{
return new Address { City = this.City };
}
}
public class Person
{
public string Name { get; set; }
public Address Address { get; set; }
public Person DeepCopy()
{
return new Person
{
Name = this.Name,
Address = this.Address.DeepCopy() // Deep Copy
};
}
}
Deep Copy Output
--- Test Deep Copy: Started ---
Person1: John, New York
Person2: Doe, Los Angeles
--- Test Deep Copy: End ---
Explanation
- A Person object (person1) is created with the Name "John" and an Address object referencing "New York".
- A deep copy (person2_DeepCopy) is created using the DeepCopy method. The Address object is also independently duplicated.
- Changes to person2_DeepCopy.Address.City does not affect a person1.Address.City, as they are completely independent.
Key Differences: Shallow Copy vs. Deep Copy
Aspect |
Shallow Copy |
Deep Copy |
Object Copy |
Duplicates only the top-level object. |
Duplicates the top-level object and referenced objects. |
References |
Shared between the original and copied objects. |
Independent for each object. |
Impact of Changes |
Changes to referenced objects affect both copies. |
Changes are isolated between copies. |
Implementation |
Uses MemberwiseClone(). |
Requires a custom implementation. |
When to Use?
- Shallow Copy: Use when
- The object has simple structures.
- Shared references are acceptable or desirable.
- Deep Copy: Use when
- The object has complex, nested structures.
- Independent copies are essential.
Conclusion
Understanding when to use a shallow or deep copy depends on your application's needs. While a shallow copy is quick and efficient, it may lead to unintended changes in shared references. A deep copy provides complete independence but requires more effort to implement. Use the examples provided here to choose the appropriate approach for your scenario!