skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Copy a record, change one thing

C# 9

Code card copying Khalid's Person record with Name changed to Nicole. The copy prints with Planet Earth and compares unequal to the original.

A with expression copies a record and changes only the properties you name. Records compare by value. It is available since C# 9. The key line is var nicole = khalid with { Name = "Nicole" } in records.cs. Run it and the output reads Person { Name = Nicole, Planet = Earth }, False.

Did this tip save you some time? Consider buying me a coffee to fuel the next one.

Buy me a coffee
records.cs
var khalid = new Person("Khalid", "Earth");
var nicole = khalid with { Name = "Nicole" };
Console.WriteLine(nicole);
Console.WriteLine(khalid == nicole);
record Person(string Name, string Planet);
Output
$ dotnet run records.cs
Person { Name = Nicole, Planet = Earth }
False