Primary Constructors in C# 12
As we bid farewell to the older syntax, let’s embrace the newer, more expressive way of creating objects.
Published in
3 min readMar 22, 2024
Introduction
In C# 12, primary constructors play a crucial role in defining the behaviour of classes and structs. By adding parameters to a struct or class declaration, you can create a primary constructor.
Use Cases
- Base Constructor Invocation: Pass primary constructor parameters as arguments to a base constructor invocation. This allows for seamless initialization of base class properties.
- Member Field Initialization: Primary constructor parameters are often used to initialize member fields or properties. By directly assigning values during construction.
Getting Started
The struct & constructor declaration before C# 12. Please find below the example of the older syntax.
public readonly struct Distance
{
public readonly double Magnitude { get; }
public readonly double Direction { get; }
public Distance(double dx, double dy)
{
Magnitude = Math.Sqrt(dx * dx + dy * dy);
Direction = Math.Atan2(dy, dx);
}
}