Post
C# 7.1 - New features
Introduction
In some of the previous posts we talked about new features in C# 7 and we talked about the usage of nameof expression in C#. In this post, we will talk about new features that came with C# 7.1.
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
- Build
- Scroll down and click on Advanced
- Set Language version to 7.1 or latest minor version
- Save
Or you can add the following to your .csproj file:
<PropertyGroup>
<LangVersion>7.1</LangVersion>
</PropertyGroup>
Or use latest minor version:
<PropertyGroup>
<LangVersion>latest</LangVersion>
</PropertyGroup>
async Main
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:
https://gist.github.com/Ibro/74c7713ac6b5fd430b680cf182e2efa3
Now we can simply mark the Main method as async:
https://gist.github.com/Ibro/53f0d3e218f81e104d3d88046b05a86f
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
default literal expressions
If we had a function that used default expression, something like this:
https://gist.github.com/Ibro/4b1787437dc0ec55c16764a68f3bad4b
With C# 7.1 we can simplify the default expression:
https://gist.github.com/Ibro/f864e9d00ed5ebd4f32d8c0eb76d0621
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:
https://gist.github.com/Ibro/3d3fbfae19de6b9d6845e96682f88034
In C #7.1 there is a small enhancement which can come in handy. When declaring Tuple we can infer element names:
https://gist.github.com/Ibro/2c222c7de2b4ca201ac5b394059853d9
That result is equal to declaring tuple with its elements explicitly named:
https://gist.github.com/Ibro/9904f918e12171d4fda0a08eaad72021
This might remind you of JavaScript feature that arrived with ES6 / ES2015 - Property Shorthand:
https://gist.github.com/Ibro/b3128f4d7e1cc1ee9dbd9bd9a2ea5f5a