with and record types in C# 9.0

In the previous post we looked at the new C# record type. Whilst we can make record types mutable, they’re particularly well suited to immutability. When used as immutable types we need a way to make new immutable types based upon previous ones.

Let’s use our Person record type from the previous post but sprinkled with C# 9 goodness in the form of init

public record Person
{
   public string FirstName { get; init; }
   public string LastName { get; init; }
}

The init syntax gives us the ability to create instances of a Person, assigning values during the construction phase of the record type using standard initialiser syntax.

For example

var p = new Person 
{ 
   FirstName = "Scooby", 
   LastName = "Doo" 
};

However, this post is mean’t to be about the with keyword with allows us to take a record type and create a new instance baed upon and existing record with changes. i.e. we want to take the Person p and create a new record with the FirstName = “Scrappy”, like this

var scrappy = p with { FirstName = "Scrappy" };

the result of outputting this to the console would be

Person { FirstName = Scrappy, LastName = Doo }