Tech News
← Back to articles

Unexpected inconsistency in records – Jon Skeet's coding blog

read original related products more articles

Unexpected inconsistency in records

The other day, I was trying to figure out a bug in my code, and it turned out to be a misunderstanding on my part as to how C# records work. It’s entirely possible that I’m the only one who expected them to work in the way that I did, but I figured it was worth writing about in case.

As it happens, this is something I discovered when making a change to my 2029 UK general election site, but it isn’t actually related to the election, so I haven’t included it in the election site blog series.

Recap: nondestructive mutation

When records were introduced into C#, the “nondestructive mutation” with operator was introduced at the same time. The idea is that record types can be immutable, but you can easily and efficiently create a new instance which has the same data as an existing instance, but with some different property values.

For example, suppose you were to have a record like this:

public sealed record HighScoreEntry(string PlayerName, int Score, int Level);

You could then have code of:

HighScoreEntry entry = new("Jon", 5000, 50); var updatedEntry = entry with { Score = 6000, Level = 55 };

This doesn’t change the data in the first instance (so entry.Score would still be 5000).

... continue reading