C# 12 new features
Primary constructors for non-record classes and structs
In C# 11 and earlier, non-record classes and structs could only be initialized using the default constructor. This meant that you had to explicitly initialize all of the properties and fields of the class or struct in the constructor body.
With C# 12, you can now add parameters to the class declaration and use them in the class body. This can help reduce boilerplate code and make it easier to initialize properties and use constructor parameters in methods and accessors.
For example, the following code shows how to use a primary constructor to initialize the Name
and Grades
properties of a Student
class:
C#
class Student {
public string Name { get; set; }
public int Grades { get; set; }
public Student(string name, int grades) {
Name = name;
Grades = grades;
}
}
Using aliases for any type
In C# 11 and earlier, you could only use aliases for named types. This meant that you could not create aliases for tuple types, array types, pointer types, or other unsafe types.
With C# 12, you can now use aliases for any type. This can make your code more readable and concise, especially when you are working with complex or unfamiliar types.
For example, the following code shows how to use an alias to create a shorter name for a tuple type:
C#
using alias MyTuple = tuple<int, string>;
MyTuple tuple = (1, "Hello");
Default values for lambda expression parameters
In C# 11 and earlier, lambda expressions could not have default values for their parameters. This meant that you had to explicitly provide a value for each parameter every time you used the lambda expression.
With C# 12, you can now specify default values for the parameters of lambda expressions. This can make your code more concise and easier to read, especially when the lambda expression is only used once.
For example, the following code shows how to use a default value for a parameter of a lambda expression:
int Add(int x, int y = 10) {
return x + y;
}
int value = Add(10); // y is set to 10 by default