What is the difference between a shallow copy and a deep copy?

C# OOP Intermediate 1–2 Yrs2–3 Yrs Conceptual 1 min read

Quick Answer

A shallow copy duplicates the top-level object but its reference-type fields still point at the same nested objects — MemberwiseClone(). A deep copy recursively duplicates everything, so the copy is fully independent. Deep copies need manual work, a serializer round-trip, or a library.

A shallow copy copies the outer object but shares its inner objects — so if the original and the copy both hold a reference to the same list, changing that list through one is visible in the other. MemberwiseClone does a shallow copy. A deep copy walks the whole object graph and duplicates everything, so the two are completely independent. There's no built-in deep copy — you either write a copy constructor, serialize and deserialize, or use a mapping library. The easiest way to avoid the problem entirely is to make the type immutable.

  • Object.MemberwiseClone() is a shallow copy — fine for a flat object, dangerous if it contains lists or child objects you then mutate.
  • Deep copy options: a hand-written copy constructor / Clone; serialize to JSON and deserialize; a mapper (AutoMapper, Mapster); record's with is shallow.
  • ICloneable is discouraged because it doesn't say whether it's shallow or deep.
  • Immutable types side-step the whole question — nothing to copy.