導入
switchやisは、値そのものだけでなく「型」「形」「条件」でも分岐できます。これがパターンマッチングです。型を調べながら変数へ取り出す、タプルの形で分岐する、and/or/notで条件を組む——現代C#で最も表現力が高い機能のひとつで、ifの山を一気に読みやすくできます。
図解
flowchart TB
V["調べたい値"] --> T["型パターン<br/>is int n"]
V --> P["プロパティ/タプルパターン<br/>(0, _)"]
V --> L["論理パターン<br/>>= 70 and < 90"]
V --> A["リストパターン<br/>[1, .., 3]"]
サンプル
// is 型パターン: 型を調べて、同時に変数へ取り出す
object value = 42;
if (value is int n)
Console.WriteLine($"整数です: {n}"); // 整数です: 42
// switch式 × 型パターン(when で追加条件も付けられる)
string Describe(object x) => x switch
{
int i when i < 0 => "負の整数",
int i => $"整数 {i}",
string s => $"文字列 {s}",
null => "null",
_ => "その他",
};
Console.WriteLine(Describe("hi")); // 文字列 hi
// タプルパターン: 複数の値の「組」で分岐
var point = (X: 0, Y: 5);
string where = point switch
{
(0, 0) => "原点",
(0, _) => "Y軸上", // _ は「何でもよい」
(_, 0) => "X軸上",
_ => "それ以外",
};
Console.WriteLine(where); // Y軸上
// and / or / not パターン
int score = 85;
string grade = score switch
{
>= 90 => "A",
>= 70 and < 90 => "B", // and で範囲を挟む
_ => "C",
};
Console.WriteLine(grade); // B
// リストパターン: 配列やリストの「形」で分岐(.. は残り全部)
int[] arr = { 1, 2, 3 };
Console.WriteLine(arr is [1, .., 3] ? "1で始まり3で終わる" : "違う"); // 1で始まり3で終わる
- 型パターン
is int n:型を判定しつつ、その型の変数に取り出す - タプル/プロパティパターン
(0, _):複数の値の組や、オブジェクトの一部を見て分岐 - 論理パターン
and/or/not:>= 70 and < 90のように条件を組み合わせる - リストパターン
[1, .., 3]:コレクションの並びの形で分岐(..は残り任意)
演習
object data = "hello";
// TODO: is 型パターンを使い、data が string のとき "文字列: 5" のように
// 「文字列: <文字数>」を出力してください("hello" は5文字)
___
- 期待される出力:
文字列: 5
ヒント1を見る
if (data is string s) とするとsに文字列として取り出せます。長さはs.Length
ヒント2を見る
if (data is string s) Console.WriteLine($"文字列: {s.Length}");
まとめ
- パターンマッチングは値だけでなく型・形・条件でも分岐できる
is 型 変数で判定と取り出しを同時に行えるand/or/not・タプル・リストパターンでifの山を簡潔にできる
次回: 決まった回数を繰り返すforです。