Switch Expressions in C# 8.0: Pattern Matching

C# 8.0’s switch expressions are more concise than traditional switch statements. They use pattern matching and return values directly.

Traditional vs Expression

// Traditional switch statement
string GetStatusText(Status status)
{
    switch (status)
    {
        case Status.Active: return "Active";
        case Status.Pending: return "Pending";
        default: return "Unknown";
    }
}

// Switch expression
string GetStatusText(Status status) => status switch
{
    Status.Active => "Active",
    Status.Pending => "Pending",
    _ => "Unknown"
};

Pattern Matching

decimal CalculateDiscount(Customer customer) => customer switch
{
    { Years: > 10 } => 0.20m,
    { Years: > 5 } => 0.10m,
    { IsPremium: true } => 0.15m,
    _ => 0m
};

Tuple Patterns

string GetQuadrant(int x, int y) => (x, y) switch
{
    (> 0, > 0) => "Q1",
    (< 0, > 0) => "Q2",
    (< 0, < 0) => "Q3",
    (> 0, < 0) => "Q4",
    _ => "Origin"
};

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.