🔧 The Record Struct Update That Changed a Copy, Not the Original
A record struct looks and behaves like a record in almost every way that matters for readability – value equality, a generated ToString, a with expression for non-destructive updates – but it’s still a struct underneath, which means it’s copied by value every time it’s passed to a method, stored in a collection’s indexer result, or read through a property that doesn’t return by reference. Code that calls a with expression or sets a property on a record struct pulled out of a list or dictionary is usually mutating a temporary copy of that element, not the element actually sitting in the collection, and the change simply vanishes.
🔎 The Problem
public record struct ScoreEntry(string Player, int Points);
var scores = new List<ScoreEntry>
{
new("Alice", 10),
new("Bob", 7)
};
// This compiles, runs, and does... nothing useful. foreach's
// loop variable is a COPY of the struct, so updating it updates
// only that copy, never the entry actually sitting in the list.
foreach (var entry in scores)
{
entry.Points += 1;
}
Console.WriteLine(scores[0].Points); // still 10, not 11
✅ Fix: Mutate Through an Index, or Replace the Element Entirely
- Accessing the list by index (scores[i] = scores[i] with { Points = scores[i].Points + 1 }) and reassigning the element works because it writes a new value back into the list’s actual storage slot, rather than mutating a disposable copy that was only ever a loop variable.
- Using a for loop with an index instead of foreach, and applying the with expression or property update directly against list[i], keeps every change aimed at the collection’s real storage rather than at a temporary value sitting on the stack.
- Switching to an ordinary record class (not a record struct) removes this entire category of mistake when a given type is going to be stored in collections and updated frequently, since a class reference is shared rather than copied every time it’s read out.
⚠️ Why the Compiler Doesn’t Flag This
- foreach deliberately uses a read-only-feeling copy for value types for safety reasons unrelated to this scenario (iterator invalidation), and the compiler has no way to know the developer’s intent was to mutate the original rather than inspect a copy.
- A record struct’s with expression is specifically designed to produce a new value rather than modify in place – which is exactly the correct, by-design behavior for a value type, even though it reads, at the call site, almost identically to how it would look updating a reference type’s property.
A record struct with expression doesn’t update anything – it hands back a brand new value, and whether that new value replaces anything real depends entirely on what you do with it next.



