➡️ switch expression is an expression, not a statement
Switch statements are verbose. Switch expressions return values. Less code, fewer bugs, no fall-through.
❌ Switch Statement
string GetGrade(int score)
{
string grade;
switch (score)
{
case >= 90:
grade = "A";
break;
case >= 80:
grade = "B";
break;
default:
grade = "F";
break;
}
return grade;
}
✅ Switch Expression
string GetGrade(int score) => score switch
{
>= 90 => "A",
>= 80 => "B",
_ => "F"
};
🎯 Advanced Patterns
// Tuple pattern
static string GetQuadrant((int x, int y) point) => point switch
{
(0, 0) => "Origin",
( > 0, > 0) => "Q1",
( < 0, > 0) => "Q2",
( < 0, < 0) => "Q3",
( > 0, < 0) => "Q4",
_ => "On axis"
};
// Type pattern + property pattern
static decimal CalculateDiscount(object item) => item switch
{
Product { Category: "Electronics", Price: > 1000 } p => p.Price * 0.10m,
Product { Category: "Books" } p => p.Price * 0.15m,
Product p => p.Price * 0.05m,
null => 0,
_ => throw new ArgumentException()
};
// When guard
static string Classify(int number) => number switch
{
< 0 => "Negative",
0 => "Zero",
> 0 and < 10 => "Small positive",
>= 10 and < 100 => "Medium positive",
_ => "Large positive"
};
💡 Benefits
- Expression body (no statements)
- No fall-through bugs (=> handles it)
- Exhaustiveness checking (compiler warns if missing cases)
- Can be used in LINQ, lambdas, initializers
- Much less code, same logic
“50-line switch statement became 10-line switch expression. Removed all ‘break’ bugs. Compiler checks exhaustiveness. Switch expressions are how C# should have always worked.”
