Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Object Copying: Shallow vs Deep Copy

Learn how to copy objects in C# correctly. Compare shallow and deep copy approaches, understand reference semantics, and choose the right strategy.

~6 min readC#
#C##Object Copying#Deep Copy#Shallow Copy
Diagram showing two objects sharing references versus independent copies in C#

When you copy an object in C#, the result depends on whether you copy the reference or the underlying data. A simple assignment copies the reference, not the object. This article covers the common approaches to C# object copying, including shallow copy with MemberwiseClone, deep copy via manual construction or serialization, and the copy behavior of records.

Reference Semantics and the Assignment Trap

C# classes are reference types. When you write var second = first;, you are not creating a copy of the object; you are creating a second reference to the same instance. Any property or field change made through second is visible through first. This is the root reason why explicit copying is needed in many applications.

csharp
public class Person { public string Name { get; set; } public Address Address { get; set; } } var first = new Person { Name = "Alice", Address = new Address { City = "Berlin" } }; var second = first; second.Name = "Bob"; second.Address.City = "Hamburg"; Console.WriteLine(first.Name); // Bob Console.WriteLine(first.Address.City); // Hamburg

Both variables point to the same object. To avoid this, you need a deliberate copying mechanism.

Shallow Copy with MemberwiseClone

The simplest built-in way to create a shallow copy is MemberwiseClone, a protected method on System.Object. It creates a new object and copies all non-static fields. For value-type fields, the values are copied. For reference-type fields, only the references are copied, so the new object and the original share the same referenced instances.

csharp
public class Person : ICloneable { public string Name { get; set; } public Address Address { get; set; } public object Clone() { return this.MemberwiseClone(); } }

Calling Clone() returns a new Person instance as an object, with the same Name value and the same Address reference. Changing a property on the shared Address instance through either object affects both, but assigning a new Address to one object's property does not affect the other. This is acceptable when the nested objects are immutable or when sharing is intentional, but it often causes subtle bugs.

Deep Copy: Manual Construction and Copy Constructors

A deep copy creates a new object graph where mutable reference-type fields are duplicated rather than shared. The most reliable way is to manually construct the copy, explicitly copying each field. This gives you full control over what is shared and what is duplicated.

csharp
public class Person { public string Name { get; set; } public Address Address { get; set; } public Person Copy() { return new Person { Name = this.Name, Address = new Address { City = this.Address.City } }; } }

Copy constructors are a common pattern. They take an instance of the same type and initialize the new object from it. This approach is explicit, maintainable, and does not rely on reflection or serialization. The downside is that you must update the copy logic whenever a new field is added.

Deep Copy via Serialization

Serialization-based deep copy writes an object to a serialized form and then deserializes it into a new instance. It can often copy an entire object graph without writing copy logic for each field, but it has costs and constraints that depend on the serializer.

csharp
using System.Text.Json; public static T DeepCopyJson<T>(T source) { var json = JsonSerializer.Serialize(source); return JsonSerializer.Deserialize<T>(json); }

With System.Text.Json, the type does not need to be marked [Serializable], but deserialization normally requires a constructor the serializer can use. For many classes that means a public parameterless constructor; parameterized constructors and records can work with matching parameter names or custom configuration. JSON serialization does not preserve object identity for shared references, and it throws on circular references by default. It is typically much slower than manual copying and is best used for simple graphs, cross-boundary data, or prototyping. The older BinaryFormatter is another serialization option, but it is obsolete for security reasons and should not be used for copying in modern .NET.

Records and with Expressions

C# 9 introduced records, which are reference types with built-in value semantics for equality. Records provide a with expression that creates a shallow copy with optional property changes. This is a convenient way to copy immutable data structures.

csharp
public record Person(string Name, Address Address); var original = new Person("Alice", new Address("Berlin")); var modified = original with { Name = "Bob" };

The modified record has the same Address reference as original. If you need a deep copy of a record, you must still copy the nested reference types manually or use another technique. Records are ideal when you want copy-and-update semantics for immutable data, but they do not solve deep copying by themselves.

Performance and Allocation Tradeoffs

The choice of copying strategy has direct performance implications. MemberwiseClone is fast because it is a low-level field-by-field copy. Manual copy constructors are also fast, but they require you to write and maintain the code. Serialization-based copying is the slowest because it involves reflection, allocation of intermediate buffers, and often string parsing.

ApproachSpeedDepthMaintenanceCircular References
MemberwiseCloneFastShallowLowPreserved
Manual constructorFastDeepHighManual handling
SerializationSlowDeepLowOften problematic
Records + withFastShallowLowPreserved

If you are copying large object graphs frequently, avoid serialization. If you need deep copies and the object graph is stable, a manual copy method is the most predictable and efficient. For simple shallow copies, MemberwiseClone or records with with are appropriate.

Choosing the Right Copy Strategy

There is no universal best way to copy objects in C#. The correct approach depends on the type's structure, whether the object graph contains cycles, whether you need immutability, and how often copying occurs.

Use MemberwiseClone when you need a quick shallow copy and you understand that nested references will be shared. Use records with with when you are working with immutable data and want a copy that differs in a few properties. Use a manual copy constructor or a dedicated Copy method when you need a deep copy and you can keep the copy logic in sync with the type's evolution. Use serialization only for prototyping, cross-boundary copying, or when the object graph is simple and performance is not a concern.

One often overlooked detail is that MemberwiseClone does not call any constructors. This means any initialization logic in constructors is skipped, which can leave the copy in an unexpected state if the class relies on constructor side effects. Manual copy methods go through normal construction. A record's with expression, by contrast, copies the existing instance and does not rerun the record's declared constructor, so any validation in that constructor is not repeated.

Another consideration is inheritance and the declared return type of a copy method. MemberwiseClone is called on the original instance, so an inherited Clone() that uses it produces a copy with the original's runtime type. The problem is the method's declared return type: if Clone() is declared on a base class and returns that base type, callers on derived instances get a base-typed reference and may need a cast to access derived fields. This can be confusing when derived classes add fields. A manual copy method that uses new and explicit property assignment makes the behavior easier to keep correct across inheritance.

For types that contain collections, a shallow copy copies the collection reference, not the elements. If you need a deep copy of a List<T> or Dictionary<K,V>, you must copy the collection and each element. This is where manual copying becomes verbose, and you may want to use a generic deep-copy helper based on reflection or expression trees. However, such helpers add complexity and can break with private fields or circular references.

Ultimately, the best strategy is the one that makes the copying behavior explicit and testable. Prefer a method named Copy or Clone that clearly documents whether the copy is shallow or deep. Avoid relying on serialization in hot paths, and always verify that nested objects are handled as expected when the type changes.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.