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)
{
}
public string Make { get; set; } = make;
public int Year { get; set; } = year;
public int WheelsCount { get; set; } = wheelsCount;
}
Default Lambda Parameters
This feature lets developers add default values for Lambada parameters like the way we can do for methods in C#. In the older version of C#, we have to write local functions and couldn’t use the nice short Lambadas when we wanted to have a default value for parameters.
In the following example, you can see that we gave a default value to the addingValue
parameter, and when we don’t pass a second parameter to the function, it assigns 1
to addingValue
automatically.
var Increment = (int baseValue, int addingValue = 1) => baseValue + addingValue;
Console.WriteLine(Increment(3)); // 4
Console.WriteLine(Increment(3, 2)); // 5
Alias Any Type
This feature will let you assign alias names to already existing C# types, so it will make more sense in the future why a type was used for a specific reason in the code base.
using Point = (int X, int Y, int Z);
using FilePaths = string[];
Conclusion
Over the past few years, the C# development team has implemented a variety of new features to enhance the language’s efficiency and readability. As a result, C# is poised to remain relevant for future projects and will require less code to accomplish more.