Top 5 C# 8.0 Features with examples


C# 8 Features

C# was first introduced with .NET Framework 1.0 in 2002(stable version). Since its emergence it is enhancing with each release.

In September 2019 Microsoft has announced its 8th version, i.e. C# 8 with lot of new and important features.

In this article most frequently used features of C# 8.0 are described.

For more details, please check the below link:
https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8


Prerequisites

In this article I have used Visual Studio 2019 and .NET Core Version 3.0 to elaborate the C# 8 features.


Features of C# 8:

  • Nullable reference types

Inside a nullable annotation context, any variable of a reference type is considered to be a nonnullable reference type. If you want to indicate that a variable may be null, you must append the type name with the? to declare the variable as a nullable reference type.

To declare variable /property as Nullable, we have to add “#nullable enable “ in our code.


  • Default interface methods

We can now add members to interface and provide implementation for those members.

To use this feature of C# 8, we have to use .NET Core 3x which is available in Visual Studio 2019.



  • Switch Statement

We can initiate switch statement in a new easy way




Key points :

  • No "case" and "break" keywords.
  • colon ":" is replaced by "=>"
  • default is replaced by underscore "_"

  • Asynchronous streams

Now we can iterate using “await” over “async” collection


  • Null – coalescing assignment

C# 8.0 introduces the null-coalescing assignment operator ??=. You can use the ??= operator to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null.