Microsoft introduced several new features in C# 12, which is part of .Net8 enhances the language's capabilities and makes development more efficient1. Please find below the some of the new features introduced in C# 12.
1. Primary Constructors for All Types
Primary constructors are now available for all classes and structs, not just records. This simplifies the syntax for initialising fields.
public class Employee(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
}
2. Collection Expressions
Collection expressions provide a concise way to create collections like arrays, lists, and spans.
var numbers = [1, 2, 3, 4, 5];
var words = ["hello", "world"];
var chars = ['a', 'b', 'c'];
3. Default Values for Lambda Parameters
You can now specify default values for lambda parameters.
Func<int, int, int> add = (x, y = 0) => x + y;
Console.WriteLine(add(5));// Output: 5
Console.WriteLine(add(5, 3)); // Output: 8
4. Inline Arrays
Inline arrays allow you to define arrays directly within expressions.
var inlineArray = new[] { 1, 2, 3 };
5. Alias Any Type
You can now use aliases for any type, making working with complex type names easier.
using System.Collections.Generic;
using IntList = System.Collections.Generic.List<int>;
IntList numbers = new IntList { 1, 2, 3 };
6. Experimental Attribute
The experimental attribute allows you to mark features that are still in development.
[Experimental]
public void MyExperimentalMethod()
{
// Experimental code here
}
7. Interceptors
Interceptors provide a way to intercept method calls and modify their behavior.
public class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Before method call");
invocation.Proceed();
Console.WriteLine("After method call");
}
}
8. Improved switch Expressions
Switch expressions have been enhanced to be more concise and readable.
var value = 1;
var result = value switch
{
1 => "One",
2 => "Two",
_ => "Other"
};
9. Enhanced using Directives
Using directives has been improved to allow more flexibility in organising imports.
using static System.Console;
WriteLine("Hello, World!");
These new features in C# 12 make the language more powerful and expressive, helping developers write cleaner and more efficient code.