rksoftware

Visual Studio とか C# とかが好きです

C# 2.0 以降の新機能の確認 - C# 9.0 - パターン マッチングの拡張機能

C# 2.0 以降の新機能を一つづつ確認していきます。
以前に一度行ったのですが、公式ドキュメント再編でリンク切れしているところを見つけてしまったので。今ならもっと簡潔なサンプルが欠けるところもあるだろうし、せっかくなので今もう一度確認して行きます。

パターン マッチングの拡張機能

 https://docs.microsoft.com/ja-jp/dotnet/csharp/tutorials/pattern-matching#add-peak-pricing
 パターンマッチングが強化された。

// a に関する条件を a を何度も書かずに
int a = new Random().Next();
if (a is (> 1 and < 3) or (> 100 and < 200)) Console.WriteLine("match");

// 否定は not。null のチェックに使うのがおすすめらしい
string b = null;
if (b is not null) Console.WriteLine("not null");

// switch 式ですごいことに
string Method(object arg)
{
    var text = arg switch
    {
        > 1 => "> 1",
        "a" => "a",
        not null => "not null",
        _ => "null",
    };
    return text;
}
Console.WriteLine(Method(0));