DEV Community

Cover image for Deep Copy vs. Shallow Copy in C# – What’s the Difference?
Daniel Azevedo
Daniel Azevedo

Posted on

Deep Copy vs. Shallow Copy in C# – What’s the Difference?

Hi devs,

When working with objects in C#, understanding how to copy them is crucial, especially when you want to avoid unexpected side effects in your code. In this post, I'll explain the differences between shallow copy and deep copy, and when to use each. I’ll also walk you through some practical C# examples to illustrate how they work in real-world scenarios.


What is Shallow Copy?

A shallow copy is a copy of an object where only the top-level object is duplicated, while any references to other objects inside it still point to the same memory location. Essentially, a shallow copy creates a new object but reuses references to the objects inside.

This can lead to unintended consequences if you're not careful. For example, modifying a property inside the original object will affect the copy as well (and vice versa), because they both share the same reference to the inner object.

Example of Shallow Copy in C#:

Let’s start by looking at an example:



public class Employee
{
    public string Name { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string City { get; set; }
}

class Program
{
    static void Main()
    {
        // Original object
        Employee emp1 = new Employee
        {
            Name = "John",
            Address = new Address { City = "New York" }
        };

        // Shallow copy
        Employee emp2 = (Employee)emp1.MemberwiseClone();

        // Modify the city of emp2's address
        emp2.Address.City = "Los Angeles";

        // Output
        Console.WriteLine(emp1.Address.City); // Output: "Los Angeles"
    }
}


Enter fullscreen mode Exit fullscreen mode

In this example:

  • We create an Employee object (emp1) and perform a shallow copy using the MemberwiseClone() method.
  • Both emp1 and emp2 share the same reference to the Address object.
  • Changing emp2.Address.City also affects emp1.Address.City because both objects reference the same Address.

This behavior is exactly what you'd expect from a shallow copy—only the top-level object (Employee) is copied, while the inner objects (like Address) are shared.


What is Deep Copy?

A deep copy, on the other hand, duplicates not only the top-level object but also all the nested objects. It creates an entirely independent copy, meaning changes to the inner objects in the copy won’t affect the original object (and vice versa).

Example of Deep Copy in C#:

To achieve a deep copy, we need to explicitly clone the nested objects as well. Here's how we can do that:



public class Employee
{
    public string Name { get; set; }
    public Address Address { get; set; }

    // Method to create a deep copy
    public Employee DeepCopy()
    {
        Employee clone = (Employee)this.MemberwiseClone();
        clone.Address = new Address { City = this.Address.City };
        return clone;
    }
}

public class Address
{
    public string City { get; set; }
}

class Program
{
    static void Main()
    {
        // Original object
        Employee emp1 = new Employee
        {
            Name = "John",
            Address = new Address { City = "New York" }
        };

        // Deep copy
        Employee emp2 = emp1.DeepCopy();

        // Modify the city of emp2's address
        emp2.Address.City = "Los Angeles";

        // Output
        Console.WriteLine(emp1.Address.City); // Output: "New York"
    }
}


Enter fullscreen mode Exit fullscreen mode

In this case:

  • The DeepCopy() method creates a completely independent copy of Employee, including the Address object.
  • Modifying the Address in emp2 does not affect emp1—the two objects are now fully independent.

When to Use Shallow vs. Deep Copy?

So, when should you use a shallow copy, and when is a deep copy necessary? It all depends on the complexity of the objects you're dealing with and whether you want the copy to share references to inner objects.

Use Shallow Copy When:

  • The objects you're copying don't contain nested objects (or the nested objects don’t need to be independent).
  • You want to improve performance by reusing inner objects where possible.

Use Deep Copy When:

  • You need a fully independent copy where changes to the copied object don’t affect the original object.
  • You’re dealing with complex, nested objects where maintaining reference integrity is critical.

Common Pitfalls

1. Forgetting to Implement Deep Copy

It’s easy to assume that copying an object will also copy its contents, but as we saw with the shallow copy example, this isn’t the case. If your object contains nested objects and you forget to implement deep copy logic, you might end up with bugs where changes in one object unexpectedly affect others.

2. Performance Considerations

While deep copying gives you full independence between objects, it comes at a performance cost, especially if the objects are large or deeply nested. You should be mindful of when deep copying is necessary and optimize for performance when possible.


Conclusion

The difference between shallow copy and deep copy is subtle but important. A shallow copy only copies the top-level object, while a deep copy duplicates everything, including nested objects. Choosing the right method depends on whether or not you need the copies to be independent.

  • Shallow Copy is faster but shares references to nested objects.
  • Deep Copy ensures full independence but is more expensive in terms of performance.

Understanding when to use each approach can help you avoid bugs and improve the reliability of your code. Hopefully, these examples give you a clearer understanding of how both techniques work and when to apply them!

Keep coding :)

Top comments (0)