C# Interview Question #105

What is the difference between shallow copy and deep copy?

Types, Equality, Immutability & Internals Senior Advanced

Quick Interview Answer

A shallow copy creates a new outer object but copies references to nested reference-type objects. Therefore, the original and copy may still share child objects.

Detailed Explanation

A shallow copy creates a new outer object but copies references to nested reference-type objects. Therefore, the original and copy may still share child objects.

A deep copy creates independent copies of the nested mutable objects as well, so modifying a child in one graph does not affect the other.

C# does not provide one universal deep-copy operation because correct copying depends on the object's semantics. Copy constructors, mapping code, records, and explicit clone methods are usually clearer than serialization-based cloning.

Code Example

var copy = new Customer
{
    Name = original.Name,
    Address = new Address
    {
        City = original.Address.City
    }
};