C#•Switch Expressions
C# Switch Statements and Modern Switch Expressions (C# 8+)
Switch expressions replace verbose switch/case/break blocks with clean functional pattern matching.
Syntax
var result = input switch {
val1 => "res1",
_ => "default"
};
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| => | Arrow Syntax | Yields result for matching pattern. |
| _ | Discard Pattern | Matches any value (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() {
string httpMethod = "POST";
// Modern C# 8+ Switch Expression
string actionDescription = httpMethod switch {
"GET" => "Fetching requested entity",
"POST" or "PUT" => "Mutating / saving server resource",
"DELETE" => "Purging database record",
_ => "Unsupported HTTP verb: " + httpMethod
};
Console.WriteLine($"Method: {httpMethod}");
Console.WriteLine($"Action: {actionDescription}");
}
}Expected Output:
Method: POST Action: Mutating / saving server resource
How It Works: Step-by-Step
- Lines 7-13: Switch expression evaluates httpMethod with => arrows.
- Line 9: Uses C# 9 pattern combinator "or" to match multiple cases.
Key Concepts
- Switch expressions are concise and return values directly.
- The discard pattern _ acts as the default fallback.
Common Mistake: Missing discard pattern _ in switch expression
If no case matches and _ is omitted, C# throws SwitchExpressionException at runtime.
❌ Incorrect
var r = x switch { 1 => "One" }; // Crashes if x is 2!✅ Correct
var r = x switch { 1 => "One", _ => "Other" };Related C# Tutorials & Compiler
C# Pattern Matching Switch Statements and Expressions
Implement modern C# pattern matching switch expressions (=>) with relational ranges, logical combinators (and/or), and discard guards.
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.