What's new in C# 7.1、Welcome to C# 7.1 をベースに、C# 7.0 と比較してコードがどう変わるのかを記載しています。
1. async
Main
メソッド (async
Main
method)
old
static void Main() {
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync() {
... // await code
}
new!
static async Task Main() {
... // await code
}
※ Main
メソッドに async
を修飾できるのは、戻り値の型が Task
or Task<int>
の場合のみです。async void Main
はコンパイルエラー CS5001 となります。詳細はこちら。
2. default
リテラル式 (default
literal expressions)
old
Func<string, bool> whereClause = default(Func<string, bool>);
new!
Func<string, bool> whereClause = default;
3. 推論されたタプル要素の名前 (Inferred tuple element names)
別名、タプル プロジェクション初期化子 (Tuple projection initializers)。
old
int width, height;
...
var rect = (width:width, height:height);
Console.WriteLine($"{rect.width}x{rect.height}");
new!
int width, height;
...
var rect = (width, height);
Console.WriteLine($"{rect.width}x{rect.height}");
4. pattern-matching with generics
C# 7.0 パターンマッチングの bug-fix レベルの変更。
以前はオープン型の式(変数)のマッチングが行えませんでしたが、C# 7.1 で対応されました。
old
public interface IShape {}
public struct Rectangle : IShape {}
public void Draw<T>(T shape) where T: IShape {
// キャストが必要。外すとコンパイルエラー。
if ((IShape)shape is Rectangle rect1) {
...
}
// キャストが必要。外すとコンパイルエラー。
switch ((IShape)shape) {
case Rectangle rect2:
...
break;
}
}
new!
public interface IShape {}
public struct Rectangle : IShape {}
public void Draw<T>(T shape) where T: IShape {
if (shape is Rectangle rect1) {
...
}
switch (shape) {
case Rectangle rect2:
...
break;
}
}
For more information
- What's new in C# 7.1 | Microsoft Docs
- Welcome to C# 7.1 | .NET Blog
- csharplang/Language-Version-History.md at master · dotnet/csharplang > C# 7.1 (Visual Studio 2017 version 15.3)