With the release of .NET 8 comes a new version of C#. Let’s summarize the key new features along with some practical examples. Will keep this post and just highlight the key parts of this release.
Primary Constructors
public class Cat(string name)
{
public string Name { get; } = name;
}
public struct Dog(string name)
{
public string Name { get; set; } = name;
}
We can now use primary constructors to initialize classes and structs.
Collection Expressions
Cat[] array = [new Cat("Snow"), new Cat("Blacky")];
List<Cat> list = [new Cat("Snow"), new Cat("Blacky")];
A lot of enumerables can now be initialized in this way.
Alias Any Type
using Point = (int x, int y);
public void Method()
{
var point = new Point(1, 2);
Console.WriteLine(point.y); // 2
}
Instead of creating an anonymous value tuple, we can now declare it at the top of our file before using it.
Optional Lambda Parameters
var addWithDefault = (int addTo = 2) => addTo + 1;
addWithDefault(); // 3
addWithDefault(5); // 6
var numbers = (params int[] xs) => xs.Length;
numbers(); // 0
numbers(1, 2, 3); // 3
It is now possible to add default values to parameters inside Lambda expressions.
There are more new features but I do not believe they are useful to most developers. Check out all the new features here:
Primary constructors – C# 12.0 draft feature specifications | Microsoft Learn
Hope you find these useful!
Leave a comment