- Published on
Explore C# 12 in .NET 8
- Authors
- Name
- Martin Staael
- @staael
Exploring C# 12
C# 12, part of the .NET 8 release, introduces impactful features that enhance coding efficiency and flexibility. Here’s a closer look at what’s new.
1. Primary Constructors
Primary constructors have quickly become a favorite of mine. They are now available for all class and struct types, significantly simplifying the initialization process:
public class MyClass(int id, string name)
{
public int Id { get; } = id;
public string Name { get; } = name;
}
// Usage:
var obj = new MyClass(1, "C# 12");
2. Collection Expressions
C# 12 supports collection expressions, making collection initialization more concise and expressive:
var numbers = [1, 2, 3, 4, 5];
3. Inline Arrays
Inline arrays allow direct definition of arrays within methods or constructors, minimizing allocations:
var inlineArray = stackalloc int[] { 1, 2, 3, 4, 5 };
4. Optional Parameters in Lambda Expressions
C# 12 allows optional parameters in lambda expressions, providing greater flexibility:
Func<int, int, int> add = (a = 1, b = 2) => a + b;
// Usage:
Console.WriteLine(add()); // Outputs 3
ref readonly
Parameters
5. ref readonly
parameters enable passing parameters by reference while ensuring they remain read-only:
void ProcessData(ref readonly int data)
{
// data cannot be modified here
}
6. Alias Any Type
You can now alias any type in C# 12, improving code readability and maintainability:
using MyAlias = System.Collections.Generic.Dictionary<string, int>;
7. Experimental Attribute
The [Experimental]
attribute marks APIs as experimental, signaling that they may change in the future:
[Experimental("This feature is experimental and may change.")]
public void ExperimentalMethod() { }
8. Interceptors (Preview Feature)
Interceptors allow methods to intercept calls to other methods, providing hooks for pre- and post-processing logic:
[InterceptsLocation("MyNamespace.MyClass.Method")]
public static void Interceptor()
{
// Interceptor logic
}
Summary
C# 12 is packed with features that enhance both the language’s expressiveness and your productivity as a .NET developer. From primary constructors and collection expressions to powerful new tools like interceptors and the [Experimental]
attribute, these updates make your code more concise, readable, and maintainable. Be sure to explore these features in your projects to fully leverage what C# 12 and .NET 8 have to offer.
For more details, refer to the C# 12 documentation and the Microsoft .NET Blog.