What's new in C#12
The end of the year traditionally brings a new version of .NET and C#. This year’s updates have just been released! Microsoft describes this release as offering a simpler composition and better performance. Let’s calmly examine the most important aspects of C# 12 and find out what new features this update brings.
Collection Expressions
Until now, collections in C# have been created in many different ways. For example:
int[] x1 = new int[] { 1, 2, 3, 4 };
int[] x2 = Array.Empty<int>();
In C# 12, collection expressions are available, which standardize the syntax for creating collections:
int[] x1 = [1, 2, 3, 4];
int[] x2 = [];
So, no matter what type of collection is needed, the syntax will be the same, and the compiler will optimize data usage.
Primary Constructors
One of the key improvements introduced in C# 12 is the availability of primary constructors for all classes and structures, not limited to the record type.
A primary constructor is defined by adding parameters to the class name:
public class Item(string name)
{
public string Name => name;
}
Parameters passed in this way can be used throughout the class body, for instance, to initialize properties or fields. Such a constructor indicates that these parameters are required in every instance of the type and must be provided.
Default Parameters in Lambda Expressions
C# 12 also introduces support for default parameters in lambda expressions. The syntax and operating rules are similar to adding default values for arguments of any method or local function.
Aliases for Any Types
Another significant improvement in C# 12 is the ability to create aliases for any types using the ‘using’ directive. Now, it’s possible to create aliases for types such as tuples, arrays, pointers, and other types that were previously unavailable for aliases.
Inline Arrays
Inline arrays are an important feature introduced in C# 12, aimed at increasing application performance. The documentation does not indicate that we will deal with their declaration on a daily basis, but rather that we will have slightly faster libraries. This is because they allow for the creation of arrays of fixed size within a struct type, making the whole more efficient.
Modifying Code with Interceptors
C# 12 introduces an experimental method called “interceptors”, which allows for capturing and modifying code at compile time. Interceptors are primarily used in generating source code. It is unknown what its future will be in subsequent versions, so it’s better not to test this method in a production environment!
If you’ve had the chance to test it, we encourage you to share your experiences in the comments.