Tip #004
Copy a record, change one thing
About this tip
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.
Learn more
Did this tip save you some time? Consider buying me a coffee to fuel the next one.
Buy me a coffeeCode
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.csPerson { Name = Nicole, Planet = Earth }False