.NET 5 was released in November 2020. With it came C# 9. In this article we’re taking a look at a few new features of this (at the time of publishing) latest installment of C#.
Please notice: in order to be able to use C# 9 in your projects you need to install the .NET 5 on your machine and also target your project for .NET 5 as well. Click here for instructions on how to install and target .NET 5.
Updated pattern matching
In C# 9 pattern matching has become more semantic in it’s syntax, giving you the option to describe conditions and queries with words instead of symbols (!=, ==, && etc).
These keywords can be used wherever ‘is patterns’ are allowed, e.g. if statements and switch expressions.
Some of you might write this off as syntactic sugar. But depending on your preferences and coding style this can be used to increase your code’s readability where applied.
The shortened ’new’ expression
When instantiating an explicitly typed object you now have to option to use a short form of the ‘new’ expression.
Let’s say we have a POCO class describing a car:
When creating a new instance of the class, we now have an option to create the instance as such:
You can also directly assign values to the new object’s properties as usual.
And use a class constructor.
Init only setters
One of the most talked about features of C# 9 is records (which we won’t go over here since it deserves a post on it’s own). Records helps .NET developers create immutable objects, which has always been somewhat of a hassle in C#. Init only setters does somewhat the same thing.
By setting an object property’s set accessor as ‘init’, you tell your application that this property can only be set when the object is being instantiated.
Let’s recycle our car POCO class from the previous example, but modify the construction year property with an init setter:
Here we allow instances of the car class to have it’s color updated, but by using the ‘init’ as accessor we only allow the construction year to be assigned during initialization.
By adding the init setter we’ve gotten another tool to our encapsulation toolbox, allowing us to make some or all of the properties of a class immutable after instantiation. We can now expose our object properties as if they were public, yet shield them without setting them as private.
– Magnus Sundström, System developer B3 CodeRight