C#:C# Switch Statements and Modern Switch Expressions (C# 8+)
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:

ParameterTypeDescription
=>Arrow SyntaxYields result for matching pattern.
_Discard PatternMatches any value (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() {
        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

Run and test C# on Compilra

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

C# Online Compiler