Abdelmajid BACO

Nov 28, 2020

4 min read

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.0 comes with very interesting new features like record type, top-level statements and so on.
image from https://github.com/dotnet

Top-Level Statements

In C# 9, you can write your main program at the top level, immediately after using statements like the following code:

Top-Level Statements
Top-level statements
Top-Level Statements
SharpLab generated code

Target-Typed new

In C#9, you can omit the type in new expression when the object type is explicitly known.

Target-Typed new
Target-Typed and object initializer Syntax
Target-Typed new
Target-Typed and constructor

Lambda Discard Parameters

In C# 9, you can use discard(_)as an input parameter of a lambda expression if this parameter is unused.

Lambda Discard Parameters
Lambda Discard Parameters

Records

In C# 9, we have a new reference type called record that provides value equality:

Record type
Record type

Init Accessor

The init accessor makes immutable objects simple to create, by using object initializer:

Init accessor
Init accessor

With Expression

Only record type supports with expression to create a copy of a record:

With expression
With expression

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:

Covariant return types
Covariant return types

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.

Extension GetEnumerator code snippet
Extension 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:

Module Initializers code snippet
Module Initializers

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.

Learn More / Resources