🔧 C#: Fix a Record’s with Expression Not Cloning a Nested Collection
A record’s with expression produces a new instance by copying every field’s current value, but for a reference-type member like a List<T>, the ‘value’ being copied is the reference itself, not the list’s contents — so a record you just created with with and a record you copied it from end up sharing the exact same underlying list, and mutating that list through either one is visible through both, which quietly breaks the immutability a record otherwise seems to promise.
🔎 The Problem
public record Order(int Id, List<string> Items);
var original = new Order(1, new List<string> { "Widget" });
var copy = original with { Id = 2 };
copy.Items.Add("Gadget");
// original.Items now ALSO contains "Gadget" - both records point
// to the SAME List<string> instance, because `with` only copies
// the reference stored in the Items field, not the list itself
✅ Fix: Deep-Copy Mutable Members, or Use an Immutable Collection Type
- When a record’s member is a mutable reference type, clone it explicitly inside a
withexpression whenever you want an independent copy:original with { Items = original.Items.ToList() }. - Prefer an immutable collection type (
ImmutableList<T>,IReadOnlyList<T>populated once and never mutated in place) for record members generally — it removes the whole category of bug, since there’s no in-place mutation to share in the first place. - If you control the record’s definition, override its copy constructor to deep-copy specific members automatically, so every caller’s
withexpression gets the safe behavior without having to remember to clone manually each time.
🚨 Why This Is Dangerous
- Trusting a record’s value-type-like syntax to mean value-type-like semantics for every member, then shipping a bug where updating one ‘independent’ copy’s list silently corrupts data that other code still holds a reference to the supposedly original, unmodified record.
A with expression copies the fields it sees — for a reference type, the field it sees is just a pointer.
