How to use switch expressions in C#

Switch expressions in C# 8.0+ provide a concise syntax for pattern matching. Unlike switch statements, they return a value directly and use => instead of case and break.

You can use patterns like type patterns, relational patterns, and logical patterns. The underscore serves as a discard pattern, matching anything (similar to default).

Switch expressions are expressions, not statements, so they must return a value and can be used inline or assigned to variables.

Basic Switch Expression

C# Example Code
// Basic switch expression
int dayNumber = 3;
string dayName = dayNumber switch
{
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    4 => "Thursday",
    5 => "Friday",
    6 => "Saturday",
    7 => "Sunday",
    _ => "Invalid day"
};
Console.WriteLine($"Day {dayNumber}: {dayName}");

Type Patterns

C# Example Code
// With type patterns
object obj = "Hello";
string result = obj switch
{
    int i => $"Integer: {i}",
    string s => $"String: {s}",
    double d => $"Double: {d}",
    _ => "Unknown type"
};
Console.WriteLine(result);

Relational Patterns

C# Example Code
// Relational patterns
int score = 85;
string grade = score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"
};
Console.WriteLine($"Score {score}: Grade {grade}");

Logical Patterns

C# Example Code
// Multiple conditions (logical patterns)
int temperature = 75;
string weather = temperature switch
{
    < 32 => "Freezing",
    >= 32 and < 50 => "Cold",
    >= 50 and < 70 => "Cool",
    >= 70 and < 85 => "Warm",
    >= 85 => "Hot"
};
Console.WriteLine($"{temperature}°F is {weather}");

Tuple Patterns

C# Example Code
// With tuples
string GetQuadrant(int x, int y) => (x, y) switch
{
    (> 0, > 0) => "Quadrant I",
    (< 0, > 0) => "Quadrant II",
    (< 0, < 0) => "Quadrant III",
    (> 0, < 0) => "Quadrant IV",
    (0, 0) => "Origin",
    _ => "On axis"
};

Console.WriteLine($"Point (3, 4): {GetQuadrant(3, 4)}");
Console.WriteLine($"Point (-2, 5): {GetQuadrant(-2, 5)}");