LoginSignup
3
1

More than 5 years have passed since last update.

1分で分かる C# 7.1 の新機能

Posted at

What's new in C# 7.1Welcome 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
}
:arrow_down:
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>);
:arrow_down:
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}");
:arrow_down:
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;
    }
}
:arrow_down:
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

Related Posts

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1