C# Reference ยท Classes and Object-Oriented Concepts
Copying objects and ICloneable
Reference for copying objects in C#: reference assignment, shallow MemberwiseClone, deep copies, copy constructors, with expressions and why ICloneable is discouraged.
Assigning a class variable to another does not copy anything: both variables refer to the same object. To get an independent object you must create one yourself. There are two levels. A shallow copy duplicates the object's own fields, but any fields that are references still point to the same inner objects. A deep copy also duplicates everything the object owns.
.NET has an ICloneable interface with a single object Clone() method, but it does not say whether the result is shallow or deep, and it returns object, so callers must cast. The framework design guidelines recommend against using it in new public APIs. Prefer a copy constructor, a static factory, or (for records) a with expression.
var copy = original with { Name = "changed" }; // records var copy2 = new Order(original); // copy constructor
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public interface ICloneable { object Clone(); } protected object MemberwiseClone(); // on System.Object var copy = original with { Property = value }; // records and structs
| Member | Description |
|---|---|
Clone() |
Returns a copy as object. Shallow or deep is up to the implementer and is undocumented in the interface. |
MemberwiseClone() |
Protected method on every object. Creates a shallow copy without running any constructor. |
with |
Creates a copy of a record (or struct) and then applies the property initializers. Calls the compiler-generated copy constructor. |
Usage notes
- Assignment copies the reference for classes and arrays, but copies the whole value for structs. Mutating a copy of a struct never affects the original.
MemberwiseCloneis shallow. Reference-type fields, including collections and arrays, are shared between original and copy, as the first example shows. Copy them yourself for a deep copy.- No constructor runs on
MemberwiseClone. Field initializers and constructor logic are skipped, so invariants set there are not re-established; readonly fields are copied as they are. ICloneableis ambiguous. Callers cannot know whetherClone()is deep. If you must implement it (some APIs and old code require it), document the behavior and consider adding a strongly typedCopy()method next to it.withon records is shallow too. Nested mutable objects stay shared. Make nested members immutable, or use immutable collections.- Collections:
new List<T>(existing)andToArray()produce a shallow copy of the sequence; the elements themselves are not cloned. - Serialization round trips (for example with
System.Text.Json) give a deep copy of simple data, but they are slow and lose runtime-only state. They are a trick, not a design. - Immutable types need no copies. If objects cannot change, sharing them is safe; see Immutable types.
- Copy constructors are explicit and easy to read:
public Order(Order other). They work well with inheritance if each level copies its own members.