Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Fix a Record’s With Expression That Copies a Reference Instead of Deep-Copying It

- 27.09.26 - ErcanOPAK

🔧 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.

— C# Best Practice

Related posts:

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

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...

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

C#: Fix a DateTimeOffset Comparison That Silently Ignores a Different UTC Offset With the Same Insta...

C#: Fix a DateTimeOffset Comparison That Silently Ignores a Different UTC Offset With the Same Insta...

Views: 10
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

WordPress: Fix an XML Sitemap That Is Missing Pages You Know Are Published
WordPress: Recover Post Revisions That the Editor Shows as Completely Empty

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,080 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 672 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 585 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 562 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com