Exploring the Exciting New Features of C# 12

Christ khodabakhshi
2 min readApr 24, 2023

In the C# 12 Preview, several new features have been added to the language. This article will take a look at these features and examine how they can be helpful for us in the future.

Primary Constructors For Structs and Classes

We already heard about primary constructors when they were released for Record Types in C# 9. Now, the C# team has decided that we need the same functionality for Structs and Classes. This feature will reduce the amount of code needed to initialize properties in the constructor.

Following is an example of primary constructors for a Car class:

var myCar = new Car("Tesla", 2023);
Console.WriteLine($"Make: {myCar.Make}");
Console.WriteLine($"Year: {myCar.Year}");

public class Car(string make, int year)
{
public string Make { get; set; } = make;
public int Year { get; set; } = year;
}

The same example with adding constructor overload:

var myCar = new Car("Tesla", 2023);
Console.WriteLine($"Make: {myCar.Make}");
Console.WriteLine($"Year: {myCar.Year}");

public class Car(string make, int year, int wheelsCount )
{
// You have to call the :this() when you are overloading the primary constructors
public Car(string make, int year) : this(make, year, 4)
{

}…

--

--

Christ khodabakhshi

Software developer, dad, coffee fan, and keen on talking about business ideas and investments.