C# 9.0 The Main New Features Explained in Less Than 5 Minutes
Here’s a quick reminder of some of the new features of C# 9.0
C # 9 is officially released with .NET 5 on November 2020. In this article, I will introduce some of the new features that I think are interesting to know.
Top-Level Statements
In C# 9, you can write your main program at the top level, immediately after using
statements like the following code:
With top-level statements, there is no need to declare any namespace, class Program
or main
method. The compiler does all these stuff for you. Let’s use SharpLab to see the code generated by the compiler:
This new feature can be useful for novice programmers who want to learn the fundamentals of C #.
Target-Typed new
In C#9, you can omit the type in new
expression when the object type is explicitly known.
This new feature is a syntactical sugar to read clean code without duplicating the type.
Lambda Discard Parameters
In C# 9, you can use discard(_
)as an input parameter of a lambda expression if this parameter is unused.
This feature is another syntactical sugar, our code is more clean and sweet.
Records
In C# 9, we have a new reference type called record
that provides value equality:
Point record
is immutable, Its properties are read-only, you can simplify this syntax by using init
accesssor.
Init Accessor
The init
accessor makes immutable objects simple to create, by using object initializer:
init
accessor can be used with Classes, Structs and Records.
To create a copy of immutable record
, we use with
expression as shown in the following code:
With Expression
Only record
type supports with
expression to create a copy of a record:
record
type, init
accessor and with
expression make easier to work with immutable data in C#.
Covariant Return Types
In C# 9, the return type of override method can be more specific than the declaration in the base type. Look at the example bellow:
The method GetTemperature()
has return type Temperature
, the derived class France
overrides this method and return a specific type Celsius
.
Nice feature, it makes our code more flexible and extensible.
Extension GetEnumerator
In C# 9, foreach
statement can operate on variable of type IEnumerator<T>
when IEnumerator<T>
contains a public extension definition for GetEnumerator
.
Module Initializers
In C# 9, we use [ModuleInitializer]
attribute to specify methods that can be invoked before any other code in the module. Look at the example bellow:
The method targeted with this attribute must be static, parameterless, return void, accessible from the containing module, and not generic.
Conclusion
All these features aim to make programming with C # simpler, more intuitive and more accessible. The exhaustive list of new features can be found on the official repository rosely on GitHub.
Thanks for reading.