C#:C# Pattern Matching Switch Statements and Expressions
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:

ParameterTypeDescription
=> (Fat Arrow)SyntaxMaps the pattern condition directly to the resulting value.
and / or / notPattern CombinatorsCombines multiple relational checks concisely in C# 9+.
_ (Discard)PatternCatch-all wildcard pattern serving as default fallback.

Ready-to-Run Code Example

Executable in Compilra

Run 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 fallback

Related C# Tutorials & Compiler

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler