C# 9.0 record type

As of yesterday I got the updated version of Visual Studio 2019 (16.8.1) which includes .NET 5 and C# 9.0 – I don’t intend to post about every feature of C# 9.0 – for those interested simply go and take a look at What’s new in C# 9.0.

One feature that’s quite interesting is C# Records.

Record types “are a reference type that provides synthesized methods to provide value semantics for equality”. So basically we can create multiple instances of a record and compare them for equality. Here’s an example of a record type

public record Person
{
   public Person(string firstName, string lastName)
   {
      FirstName = firstName;
      LastName = lastName;
   }

   public string LastName { get; }
   public string FirstName { get; }
}

It’s that easy, we simply declare our type as a record instead of a class.

Now, if we create a couple of instances of a Person that look like this

Person person1 = new("Scooby", "Doo");
Person person2 = new("Scooby", "Doo");

and we compare them using ==/Equals, they will result in the two instances being the same (unlike with classes with would compare equality by reference).

Another feature of records, over classes is. If you use ToString() on an instance of a class you’ll see something like

TestApp.Person

For a record type you’ll instead get

Person { LastName = Doo, FirstName = Scooby }

this is facilitated by the compiler adding a PrintMembers protected method which generates this output.