Phase 3 of 30 · Topic 3.3

C# 13 Switch Expressions, Relational & Logical Patterns

1Concept

Switch expressions provide expression-bodied, concise pattern matching. RyuJIT compiles switch tables to O(1) jump tables (jump tables or binary search trees) rather than sequential O(N) `if-else` branches.

2Architecture Diagram

Input Score: 85
       │
       ▼
 [ Switch Jump Table (O(1)) ]
   ├── >= 90 ──> "Grade A+"
   ├── >= 80 ──> "Grade A"  <-- Matched in 1 CPU cycle
   ├── >= 70 ──> "Grade B"
   └── _     ──> "Grade C" 

3Code Example

C# 13 & .NET 9
using System;

public class SwitchExpressionDemo
{
    public static string EvaluateCandidate(int score, int yearsExp) => (score, yearsExp) switch
    {
        ( >= 90, >= 5) => "Principal / Staff Architect",
        ( >= 80, >= 3) => "Senior Software Engineer",
        ( >= 70, >= 1) => "Mid-Level Software Engineer",
        ( >= 60, _   ) => "Associate Developer",
        _              => "Intern / Candidate in Review"
    };

    public static void Main()
    {
        string level = EvaluateCandidate(88, 4);
        Console.WriteLine($"Candidate Evaluation: {level}");
    }
}

4Expected Output

Candidate Evaluation: Senior Software Engineer

5Key Takeaways

  • Switch expressions are exhaustiveness-checked at compile time by Roslyn.
  • Tuple patterns allow multi-variable matching without nested `if` statements.
  • RyuJIT optimizes dense integer switches into jump tables (`jmp [table + eax*8]`).