In C#, shallow copy and deep copy refer to two different ways of copying an object, especially when it contains references to other objects (complex or nested structures).
Definitions
Type
Description
Shallow Copy
Copies the object and its immediate references, but
not the objects those references point to. Both the original and the copy share the same referenced objects.
Deep Copy
Copies the object and recursively copies all referenced objects, creating a completely
independent duplicate.
Example
public class Person
{
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string City { get; set; }
}
Shallow Copy:
Person p1 = new Person { Name = "Alice", Address = new Address { City = "London" } };
Person p2 = (Person)p1.MemberwiseClone(); // Shallow copy
p2.Name is a new string (value type in effect).
p2.Address is shared with p1 — changing
p2.Address.City will also affect p1.
Deep Copy:
Person p1 = new Person { Name = "Alice", Address = new Address { City = "London" } };
Person p2 = new Person
{
Name = p1.Name,
Address = new Address { City = p1.Address.City } // New Address instance
};
p2 is fully independent of p1.
Modifying p2.Address.City will not affect p1.
Shallow Copy in .NET:
You can perform a shallow copy using:
object copy = this.MemberwiseClone();
This is protected and typically used within a class implementing ICloneable.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Definitions
Example
Shallow Copy:
p2.Nameis a new string (value type in effect).p2.Addressis shared withp1— changingp2.Address.Citywill also affectp1.Deep Copy:
p2is fully independent ofp1.p2.Address.Citywill not affectp1.Shallow Copy in .NET:
You can perform a shallow copy using:
This is protected and typically used within a class implementing
ICloneable.Deep Copy Techniques:
Summary Table
Also Read