Bisexual Pride

All C# developers should be familiar with the constructor in the following class declaration. The body of the constructor is delimited by curly braces. It assigns the value of the radius parameter to the private instance field _radius.

public class Circle
{
private double _radius;

public Circle(double radius)
{
_radius = radius;
}
}

C# 6.0 (released in 2015) introduced expression-bodied members. If the constructor can be implemented as a single statement, you can use an expression body definition to implement the constructor more concisely.

public class Circle
{
private double _radius;

public Circle(double radius) => _radius = radius;
}

At the time of writing, C# 12 is only available in the latest Visual Studio preview and the latest .NET 8 preview SDK. However, C# 12 introduces primary constructors. To declare a primary constructor, place any parameters in parentheses after the type name. This lets you implement the class body even more concisely.

public class Circle(double radius)
{
private double _radius = radius;
}

Primary constructors aren’t just for brevity. You can also use them in structs, and their parameters are in scope for the entire body of the class or struct.

The parameters to a primary constructor are in scope in the entire body of the declaring type. They can initialize properties or fields. They can be used as variables in methods or local functions. They can be passed to a base constructor.

Note that adding a primary constructor to a class prevents the compiler from declaring an implicit parameterless constructor. In addition, all explicitly declared constructors must call the primary constructor using the this() syntax. These restrictions ensure that all primary constructor parameters are definitely assigned.

For more on primary constructors, see What’s new in C# 12 and Explore primary constructors on Microsoft Learn.