40

New features in C# 8

 5 years ago
source link: https://www.tuicool.com/articles/hit/JzABriA
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

After an amazing version 7.x in 2017, a new C# is being built and it is going to include new useful features.

However, if you don’t know the new features in C# 7.x, you must read the following posts; you can’t imagine how you can improve your code using this new features:

A specific roadmap for C# is not published, but now we can check the new features coming in the official repository: https://github.com/dotnet/csharplang/issues

Nullable reference types:

A great feature was introduced in C# 6. The Null-conditional operator helps to check if an object or variable is null before accessing an internal value. For example:

int? length = mynumbers?.Length;

Unfortunately, we cannot use this feature for String Type. In this case, the feature consists in allowing the developers to declare a String type as Nullable:

String? strVar = null;
var length = strVar?.Length;

Async Streams:

Basically, async streams are the asynchronous equivalent of IEnumerable. This feature allows the developers to use the async keyword within a foreach as the following syntax:

foreach await (string s in asyncStream)

In order to use that code, you have to define the collection as IAsyncEnumerable:

async IAsyncEnumerable MethodName()

Default Interface Implementations:

Let’s start checking the following code:

Interface ICal 
{
    Void TurnOn();
}
Calculator : ICal
{
   void TurnOn()
   {
   }
}

Everything is easier using interfaces and as we know, we can use multiple implementations. But if we want to add a new method within the interface, all the classes implementing that interface need to create a local method with the same name and return the same value.

Now in C# 8, we can implement a method directly within the interface like this:

Interface ICar 
{
    Void TurnOn();
}
Car : ICar
{
   void TurnOn()
   {
   }
}
Interface ICal 
{
    Void TurnOn();
    double SumNumbers( double number1, double number2 ) 
    {
       return number1+ number2 
    }
}
Calculator : ICal
{
   void TurnOn()
   {
   }
}

Extension Everything:

This proposal was reported as an issue in github and you can see the summary in the following link:

https://github.com/dotnet/roslyn/issues/11159

For example, an extension of a class person:

extension MyPersonExtension extends Person 
{ 
   public int NumberOfFingers() 
   { 
      get { … } 
   } 
}

You can find more information in the following links:

https://www.infoq.com/news/2017/08/CSharp-8

https://channel9.msdn.com/Blogs/Seth-Juarez/A-Preview-of-C-8-with-Mads-Torgersen#time=32m11s


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK