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 / not | Pattern Combinators | C# 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#チュートリアルとコンパイラ
C# の switch 文とモダンな switch 式 (C# 8+)
簡潔な => アロー構文とパターンマッチングを備えたモダンな C# 8+ switch 式を習得します。
C# の foreach によるジェネリック List コレクション反復の仕組み
IEnumerable<T> 列挙子の状態や読み取り専用カーソルの安全性を理解しつつ、C# の foreach による List<T> 走査を習得しましょう。
C# メソッド定義の名前付き引数と省略可能な引数
デフォルト値を持つ省略可能引数と順序に依存しない名前付き引数(name: value)を使い、柔軟で明確な C# メソッドを定義します。
C# オンラインコンパイラ
Compilra IDE で開く