C# 7.1 – New features
For you to be able to use C# 7.1 features you need to have Visual Studio 2017 15.3 or later or .NET Core SDK 2.0.
You also need to modify your project settings and set C# version to 7.1.
Setting up C# version
To modify your C# version you can use Visual Studio:
- Right-click on the project -> Properties
- Scroll down and click on Advanced
- Set Language version to 7.1 or latest minor version
Or you can add the following to your .csproj file:
Or use latest minor version:
Most notable new feature in C# 7.1 is the ability to have an async Main method. Main is usually an entry point in a C# console application. Since ASP.NET Core is basically a console application in the background, that is also starting point of ASP.NET Core application. Main must be static and it doesn’t need to be public.
Previously, we needed to have an additional method that would serve as async Main method:
Now we can simply mark the Main method as async:
The Main method can either have a return type of void or int. With C# 7.1 and arrival of async Main, you can now have two more return types: Task and Task<int>.
default literal expressions
If we had a function that used default expression, something like this:
With C# 7.1 we can simplify the default expression:
Inferred tuple element names
We talked about new features regarding tuples in one of the last posts. We saw that you can have names in the Tuple result:
In C #7.1 there is a small enhancement which can come in handy. When declaring Tuple we can infer element names:
That result is equal to declaring tuple with its elements explicitly named: