C# 9 new features for methods and functions

This is the fourth article in our C# 9 series. The previous articles covered top-level programs and target-typed expressions, new features for pattern matching, and new features for methods and functions.

In this article, we’ll take a look at init accessors and records.

Init accessors

C# 9 introduces a new accessor for properties named init. The init accessor works like a public set accessor, but it can only be used during object initialization. Trying to set the property elsewhere gives a compilation error:

public class Person
{
 public string FirstName { get; init; }
 public string LastName { get; init; }
}
 
Person person = new()
{
  FirstName = "John"       // OK.
};

person.FirstName = "Jane"; // error CS8852.

init accessors can be used in the constructor. And, a body may be provided for the accessor, which can change readonly fields:

public class Person
{
 private readonly string _firstName;
 public Person(string firstName)
 {
   FirstName = firstName;
 }
 public string FirstName
 {
   get => _firstName;
   init =>
 	_firstName = value ?? throw new ArgumentNullException(nameof(value));
 }
 public string LastName { get; init; }
}

The init accessors (that are used in the object initializer) will be called after the constructor. This means we can validate the property value, but we can't validate the object as a whole because we don't know when the user has finished setting properties. If such validation is needed, init accessors cannot be used and values need to be passed as constructor arguments. Or, alternatively, an API accepting these types must validate them.

Records

C# classes are reference types. This means variables are not instances of the type, but they are references to an instance of that type (which lives on the managed heap). The default implementation of equality for reference types is to check whether two variables refer to the same instance:

class Person { public string FirstName { get; set; }};
 
Assert.False(new Person { FirstName = "John" }
         .Equals(new Person { FirstName = "John" }));

When working with objects that represent data, it can be useful to be able to compare two different instances and see if they have the same values. That is exactly what the new C# 9 records enable:

record Person { public string FirstName { get; set; }};
 
Assert.True(new Person { FirstName = "John" }
         .Equals(new Person { FirstName = "John" }));

We’ve changed the Person declaration from class to record. Now two different instances that have the same values are considered equal.

The Person record is a class for which the compiler generated an IEquatable and GetHashCode implementation that is based on the fields of the type. Doing this yourself in a class is possible, but it is tedious and error-prone.

The compiler will also generate a ToString method that returns a string with the type name, public field values and readable property values.

You can add constructors and other members to the record as you would for a regular class. Records support inheritance using the usual : syntax:

record Student : Person
{
 public int ID { get; set; }
}

The equality implementation takes into account the runtime type: A Person instance will never equal a Student instance.

C# records can be used with init accessors, which provides a convenient way to build types that cannot be modified after their creation (immutable types):

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

When working with immutable data, new values are often created by modifying existing ones. Records support this via the with expression:

Person jane = person with
{
 FirstName = "Jane"
};

The with expression copies the values from an instance and allows changing it through the init accessors. The copying relies on a copy constructor that is generated for record types.

A one-liner allows you to create an immutable record with a constructor and deconstruct method:

record Person(string FirstName, string LastName);
 
var person = new Person("John", "Doe");
(string firstName, string lastName) = person;

A body can be added to the record, to add additional members or refine the properties that would otherwise be auto-generated:

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

Conclusion

In this article, we looked at init accessors, which we can use to declare immutable properties. We then saw how records make it easy to build reference types with value semantics. By combining init accessors and records, we can build immutable data models that support change via the with expression.

Part 5 of the C# 9 series covers advanced features related to native interop and performance.

C# 9 can be used with the .NET 5 SDK, which is available on Red Hat Enterprise Linux, Red Hat OpenShift, Fedora, Windows, macOS, and other Linux distributions.

Last updated: June 17, 2021