Primary Constructors in C# 12

As we bid farewell to the older syntax, let’s embrace the newer, more expressive way of creating objects.

Sukhpinder Singh | C# .Net
.Net Programming
Published in
3 min readMar 22, 2024

--

Photo by Riku Lu on Unsplash

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

  1. Base Constructor Invocation: Pass primary constructor parameters as arguments to a base constructor invocation. This allows for seamless initialization of base class properties.
  2. 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);
}
}

Newer Syntax

--

--

Sukhpinder Singh | C# .Net
.Net Programming

.Net Developer - Editor at .Net Programming with ~48K views per month, Looking for C# writers. Link: https://medium.com/c-sharp-programming