C# 12 introduces several new features aimed at improving developer productivity and code readability. Here are some:
1. Primary Constructors:
public class Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y)
{
X = x;
Y = y;
}
}
// Now possible with C# 12:
public record Point(int X, int Y);
2. Collection Expressions:
// Old way:
List<int> numbers = new List<int>() { 1, 2, 3 };
// C# 12:
List<int> numbers = [1, 2, 3];
3. Inline Arrays:
// Old way:
int[] points = new int[] { 10, 20 };
// C# 12:
int[] points = { 10, 20 };
4. Optional Parameters in Lambda Expressions:
// Old way (required parameter):
Func<int, string> formatNumber = (x) => x.ToString();
// C# 12 (optional parameter with default value):
Func<int, string, string> formatNumber = (x, format = "G") => x.ToString(format);
5. Alias any Type:
using alias
directive.using LongType = System.Int64;
LongType myLongValue = 1234567890L;
6. ref readonly Parameters:
7. Interceptors (preview feature):
These are some of the key features introduced in C# 12. Exploring these features can help you write cleaner, more concise, and potentially more performant code.