Skip to content

Primary constructors C# 12.0code reduction

Define a constructor and backing fields with a short syntax.

Many classes in C# repeat the same pattern of defining a bunch of essential backing fields, then defining a constructor that takes values for those fields and assigns them. This is repetitive code that results in two definitions and an assignment for every parameter/field combination.

C# 12's primary constructors allow you to define a constructor and backing fields with a short syntax. The constructor parameters are automatically assigned to the backing fields.

Code

C#
class Customer(string firstName, string lastName, DateOnly dateOfBirth)
{
    public string FirstName => firstName;
    public string LastName => lastName;
    public DateOnly DateOfBirth => dateOfBirth;
}
C#
class Customer
{
    private string firstName;
    private string lastName;
    private DateOnly dateOfBirth;

    public Customer(string firstName, string lastName, DateOnly dateOfBirth)
    {
      this.firstName = firstName;
      this.lastName = lastName;
      this.dateOfBirth = dateOfBirth;
    }

    public string FirstName => firstName;
    public string LastName => lastName;
    public DateOnly DateOfBirth => dateOfBirth;
}

Notes

  • You can emit the property definitions entire and just use the primary constructor if you don't mind either the parameters being Pascal cased or the properties being camel cased

More information