DEV Community

Cover image for C# 9.0 Perks
Yuri Eastwood
Yuri Eastwood

Posted on

C# 9.0 Perks

Hello everyone!

C# 9.0 is the new kid on the block for language enthusiasts.

There are quite a few new "goodies" in it, here I'll talk a little bit about some that caught my attention, be it because it's something that will make my everyday easier or something that community has talked a lot about it and it's finally here!

I'll cover Init-only properties and accessors, target-typed new expressions and records & with-expressions.

Got all of those objects that should be set only in initialization? Problem solved!
The init accessor was just introduced to make your day easier.

Public class Product
{
    public string? Name { get; init; }
    public string? Brand { get; init; }
}
Enter fullscreen mode Exit fullscreen mode

With the aforementioned declaration any subsequent assignment to those properties will throw a compile time error!
This means that initialization onwards the state of the object is totally protected from mutation.

var product = new Product { Name = "Tomato", Brand = "XYZ" }; // YAY!
product.Brand = "GEEZ"; // NOPZ!
Enter fullscreen mode Exit fullscreen mode

And with target-type new expressions we can kiss goodbye to verbose declarations!

Product product = new { Name = "Tomato", Brand = "XYZ" };
Enter fullscreen mode Exit fullscreen mode

Which would be especially nicer if we were dealing with arrays or lists!

Product[] products = { 
    new { Name = "Tomato", Brand = "XYZ" }, 
    new { Name = "Potato", Brand = "XYZ" }, 
    new { Name = "Tomato", Brand = "GEEZ" }, 
    new { Name = "Potato", Brand = "GEEZ" }
};
Enter fullscreen mode Exit fullscreen mode

We do have a trade-off between var and target-type new expressions, but the freedom to decide what's better in each situation is what thrills me.

Continuing on our previous subject: want the whole object to be immutable, just like a value type behavior? Combine it with Record class!

Public record Product
{
    public string? Name { get; init; }
    public string? Brand { get; init; }
}
Enter fullscreen mode Exit fullscreen mode

In these cases we normally represent new states by creating a whole new object based on the values of existing ones. And this is where With-expressions come into place!

We can create the new object by only stating what's different:

Product product = new { Name = "Tomato", Brand = "XYZ" };
var otherProduct = product with { Brand = "GEEZ" };
Enter fullscreen mode Exit fullscreen mode

There are many other features that might help you out such as static anonymous functions, covariant returns and improved pattern matching. To learn more take a look in the "What's new in C# 9.0" documentation.

Top comments (0)