C#•Conditionals
C# Pattern Matching Switch Statements and Expressions
Modern C# features pattern matching switch expressions that replace verbose switch/case blocks with clean functional expressions. Switch expressions evaluate relational operators (<, >=), pattern combinators (and, or, not), type checks, and discard fallbacks (_) to yield concise, expression-bodied assignments.
Syntax
var description = statusCode switch {
200 or 201 => "SUCCESS",
>= 400 and < 500 => "CLIENT_ERROR",
>= 500 => "SERVER_FAULT",
_ => "UNKNOWN_STATE"
};
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| => (Fat Arrow) | Syntax | Maps the pattern condition directly to the resulting value. |
| and / or / not | Pattern Combinators | Combines multiple relational checks concisely in C# 9+. |
| _ (Discard) | Pattern | Catch-all wildcard pattern serving as default fallback. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
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}");
}
}
}Expected Output:
=== 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
How It Works: Step-by-Step
- Lines 11-16: Evaluates status codes using C# 9 pattern combinators (or, and, >=, <) with direct => return values.
- Lines 19-23: Demonstrates pattern matching with when guard clauses for conditional filtering.
- Line 15: Uses discard pattern _ to catch unhandled status codes safely.
Key Concepts
- Switch expressions are expressions, meaning they return a value directly and can be assigned to variables inline.
- Relational patterns allow direct comparison operators (>= 400 and < 500) without repetitive variable re-evaluations.
- The discard pattern (_) must be included when checking non-exhaustive types to avoid runtime SwitchExpressionException.
- The when guard clause allows additional boolean filters to be evaluated after a pattern matches.
Common Mistake: Omitting the discard pattern _ leading to SwitchExpressionException
If none of the switch arms match the input value and there is no default discard pattern _, C# throws a runtime System.Runtime.CompilerServices.SwitchExpressionException.
❌ Incorrect
string s = code switch { 200 => "OK" }; // Crashes with SwitchExpressionException if code is 404!✅ Correct
string s = code switch { 200 => "OK", _ => "Other" }; // Safe with discard fallbackRelated C# Tutorials & Compiler
C# Switch Statements and Modern Switch Expressions (C# 8+)
Master modern C# 8+ switch expressions with concise => arrow syntax and pattern matching.
C# Generic List Collections Iteration Mechanics via Foreach
Master generic List<T> collection traversal in C# using foreach, understanding IEnumerable<T> enumerator state and read-only cursor safety.
C# Named and Optional Parameters in Method Definitions
Define flexible C# methods using optional parameters with defaults and named arguments (name: value) for order independence and clarity.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.