動作確認環境:C# 9.0
「++C++; // 未確認飛行 C」に匿名型とis not {...} x
形式パターンマッチングの記事(リンクは記事末尾)がありました。どちらも使ったことがなかったので、自分用のサンプルコードとして。
using System; // 匿名型の作成 var t = new { a = 0, b = "", c = 1.23 }; Console.WriteLine(t.GetType()); // <>f__AnonymousType0`3[System.Int32,System.String,System.Double] // 「is not {...} x」パターンマッチング // sは省略可能です。その場合はelseのConsole.WriteLine(s);を消します。 if (t is not { c: var x } s) { // tはプロパティまたはフィールドcを持たない。 } else { // tはプロパティまたはフィールドcを持つ。 Console.WriteLine(s); // null Console.WriteLine(x); // 1.23 } // 「is not {...} x」パターンマッチング // uは省略可能です。その場合はelseのConsole.WriteLine(s);を消します。 if (t is not { c: double y } u) { // tはdouble型のプロパティまたはフィールドcを持たない。 } else { // tはdouble型のプロパティまたはフィールドcを持つ。 Console.WriteLine(u); // null Console.WriteLine(y); // 1.23 }
参考