🔧 The With Expression That Looked Like a Safe Copy and Wasn’t
A record’s `with` expression creates a new instance with specific properties changed, which feels like it should produce a fully independent copy – but it performs a SHALLOW copy, exactly like `MemberwiseClone()` does: any property that’s a reference type (a list, a nested class, a mutable object) is copied as the SAME reference, so mutating that nested object through either the original or the ‘copy’ changes it for both.
🔎 The Problem
public record Order(int Id, List<string> Items);
var original = new Order(1, new List<string> { "Widget" });
var modified = original with { Id = 2 };
modified.Items.Add("Gadget");
Console.WriteLine(original.Items.Count); // 2, not 1!
// `with` only creates a new Order wrapper - Id is a value type so it
// copies cleanly, but Items is a List<string> reference, and the with
// expression copies that REFERENCE, not the list'"'"'s contents. Both
// records now point at the exact same underlying list.
✅ Fix: Explicitly Copy Mutable Reference Properties
- Inside the `with` expression itself, explicitly create a new collection for any reference-type property that needs independence: `original with { Id = 2, Items = new List
(original.Items) }` – this is the direct, no-surprises fix for exactly this case. - For a record used often enough that remembering this every time is error-prone, prefer an immutable collection type (`ImmutableList
` instead of `List `) for the property itself – since an immutable collection can’t be mutated in place at all, the shallow-copy behavior of `with` stops being a problem, because there’s no shared mutable state left to worry about. - A custom copy constructor or a dedicated `DeepClone()` method is worth adding for records with several mutable nested properties, rather than remembering to manually deep-copy each one at every single call site that uses `with`.
⚠️ Why This Is an Easy Assumption to Make
- Records are marketed heavily around immutability and value-based equality, which creates a very reasonable (but incorrect) expectation that `with` performs a full, independent deep copy – it was never designed to, since deep-copying arbitrary nested reference types automatically isn’t something the compiler can safely assume is even correct to do.
- This bug is easy to miss in testing specifically because value-type properties (int, string, DateTime) copy correctly and behave exactly as expected – the surprising behavior only appears once a record has at least one mutable reference-type property, which many simple test records don’t have.
A record’s with expression copies the box, not everything inside it – anything that was a reference before with is still the exact same reference after.
Related posts:

C#: Fix a required Member the Compiler Enforces at Construction but a Reflection-Based Deserializer ...

C#: Fix a Dictionary Silently Returning Different Results for Equal-Looking Keys Because the Key Typ...



