Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

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

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix a Record’s with Expression Not Cloning a Nested Collection

- 17.11.26 - ErcanOPAK

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

— C# Best Practice

Related posts:

C#: Async/Await in Windows Services

C#: Async/Await in Windows Services

C#: Why Using a List Instead of a HashSet Turns Your Lookup Into a Slow Scan

C#: Why Using a List Instead of a HashSet Turns Your Lookup Into a Slow Scan

C#: Async/Await Best Practices to Avoid Deadlocks and Performance Issues

C#: Async/Await Best Practices to Avoid Deadlocks and Performance Issues

Views: 4

Post navigation

C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
SQL Server: Fix an Identity Column Gap After a Failed Bulk Insert

Leave a Reply Cancel reply

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

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,059)
  • Get the User Name and Domain Name from an Email Address in SQL (983)
  • How to add default value for Entity Framework migrations for DateTime and Bool (981)
  • Get the First and Last Word from a String or Sentence in SQL (861)
  • How to select distinct rows in a datatable in C# (856)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (658)
  • Add Constraint to SQL Table to ensure email contains @ (613)
  • Average of all values in a column that are not zero in SQL (571)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (549)
  • Find numbers with more than two decimal places in SQL (477)

Recent Posts

  • Visual Studio: Fix Quick Actions Hiding Behind a Stale Squiggle
  • Photoshop: Fix a Smart Filter Resetting After You Relink It
  • Ajax: Fix a Cancelled Request Still Updating Stale UI State
  • C#: Fix a Span Captured by a Lambda Throwing at Runtime
  • The AI Prompt That Converts a REST Endpoint Into a Typed SDK
  • Git: Fix a Worktree Locking a Branch Needed Somewhere Else
  • Asp.Net Core: Fix a Background Service Leaking Scoped Dependencies
  • SQL Server: Fix a Columnstore Index Fragmenting After Bulk Deletes
  • Docker: Fix a Container Losing Logs After a Restart Policy
  • Asp.Net Core: Fix Output Caching Serving a Stale Authorized Page

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,059)
  • Get the User Name and Domain Name from an Email Address in SQL (983)
  • How to add default value for Entity Framework migrations for DateTime and Bool (981)
  • Get the First and Last Word from a String or Sentence in SQL (861)
  • How to select distinct rows in a datatable in C# (856)

Recent Posts

  • Visual Studio: Fix Quick Actions Hiding Behind a Stale Squiggle
  • Photoshop: Fix a Smart Filter Resetting After You Relink It
  • Ajax: Fix a Cancelled Request Still Updating Stale UI State
  • C#: Fix a Span Captured by a Lambda Throwing at Runtime
  • The AI Prompt That Converts a REST Endpoint Into a Typed SDK

Social

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