C#:C# のパターンマッチング switch 文と switch 式
C#•条件分岐

C# のパターンマッチング switch 文と switch 式

モダンな C# には、冗長な switch/case ブロックを簡潔な関数型の式へ置き換えるパターンマッチング switch 式が用意されています。比較演算子 (<, >=)、パターン結合子 (and, or, not)、型チェック、破棄パターン (_) を評価して簡潔に値を返します。

構文

var description = statusCode switch { 200 or 201 => "SUCCESS", >= 400 and < 500 => "CLIENT_ERROR", >= 500 => "SERVER_FAULT", _ => "UNKNOWN_STATE" };

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
=> (Fat Arrow)Syntaxパターン条件を結果の値へ直接対応付けます。
and / or / notPattern CombinatorsC# 9 以降で複数の関係チェックを簡潔に組み合わせます。
_ (Discard)Patternデフォルトのフォールバックとして機能する包括ワイルドカードパターン。

そのまま実行できるコード例

Compilra で実行可能

C# をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

using System;

public class Program {
    public static void Main() {
        int[] testStatusCodes = { 200, 204, 404, 503, 999 };

        Console.WriteLine("=== C# Modern Pattern Matching Switch Expressions ===");

        foreach (var code in testStatusCodes) {
            // Modern C# Switch Expression with relational patterns and combinators
            string category = code switch {
                200 or 201 or 204 => "Success (2xx Fast-Path)",
                >= 400 and < 500 => "Client Error (4xx Reject)",
                >= 500 and <= 599 => "Server Fault (5xx Failover)",
                _ => "Unclassified Protocol Code"
            };

            // Expression pattern with when guard condition
            string action = code switch {
                _ when code == 200 => "Forward payload to client",
                _ when code >= 500 => "Trigger incident alert to SRE team",
                _ => "Standard audit log recorded"
            };

            Console.WriteLine($"Status {code}: {category} | Action: {action}");
        }
    }
}
期待される出力:
=== C# Modern Pattern Matching Switch Expressions ===
Status 200: Success (2xx Fast-Path) | Action: Forward payload to client
Status 204: Success (2xx Fast-Path) | Action: Standard audit log recorded
Status 404: Client Error (4xx Reject) | Action: Standard audit log recorded
Status 503: Server Fault (5xx Failover) | Action: Trigger incident alert to SRE team
Status 999: Unclassified Protocol Code | Action: Standard audit log recorded

動作のしくみ: ステップ解説

  • 11-16 行目: C# 9 のパターンコンビネータ (or, and, >=, <) と => による直接返却でステータスコードを評価します。
  • 19-23 行目: 条件付きフィルタリングのための when ガード句を用いたパターンマッチングを示します。
  • 15 行目: 未処理のステータスコードを安全に捕捉するため破棄パターン _ を使用します。

重要ポイント

  • switch 式は式であるため、直接値を返し、インラインで変数へ代入できます。
  • 関係パターンにより変数を繰り返すことなく直接比較 (>= 400 and < 500) が記述できます。
  • 実行時の SwitchExpressionException を防ぐため、網羅的でない型では破棄パターン (_) を含める必要があります。
  • when ガード句を使うと、パターン一致後に追加のブール条件を評価できます。

よくある間違い: 破棄パターン _ を省略して SwitchExpressionException が発生する

入力値に一致する switch アームがなくデフォルトの _ パターンもない場合、C# は実行時に System.Runtime.CompilerServices.SwitchExpressionException をスローします。

❌ 誤り
string s = code switch { 200 => "OK" }; // Crashes with SwitchExpressionException if code is 404!
✅ 正しい例
string s = code switch { 200 => "OK", _ => "Other" }; // Safe with discard fallback

関連するC#チュートリアルとコンパイラ

Compilra で C# を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。

C# オンラインコンパイラ