Switch Expression in C# 8.0

Last Updated : 18 Oct, 2025

Switch expressions in C# were introduced in C# 8.0. They are a more concise, readable and expressive way to handle multiple conditional branches compared to the traditional switch statement. Switch expressions can return values directly, making them suitable for assignments, return statements or inline logic.

It differs from the traditional switch statement in the following ways:

  • Returns a value directly.
  • Uses expression syntax instead of statements.
  • Eliminates the need for break or return in each branch.
  • Supports pattern matching, including type patterns, property patterns and relational patterns.

Syntax

C#
var result = input switch
{
    pattern1 => expression1,
    pattern2 => expression2,
    _ => defaultExpression
};
  • input is the value being matched.
  • pattern can be a constant, type, relational condition or property pattern.
  • _ acts as the default case, matching any unmatched values.

Example: Simple Switch Expression

C#
int number = 3;

string description = number switch
{
    1 => "One",
    2 => "Two",
    3 => "Three",
    _ => "Unknown"
};

Console.WriteLine(description); // Output: Three

Here, number switch directly returns a string based on the value of number.

Example: Pattern Matching in Switch Expressions

C#
object obj = 42;

string typeDescription = obj switch
{
    int i => $"Integer: {i}",
    string s => $"String: {s}",
    null => "Null value",
    _ => "Other type"
};

Console.WriteLine(typeDescription); // Output: Integer: 42

This demonstrates type patterns and the default _ case for unmatched types.

Example: Using Relational Patterns

C#
int score = 85;

string grade = score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"
};

Console.WriteLine(grade); // Output: B

Relational patterns allow concise comparison logic directly within the switch expression.

When to Use Switch Expressions

  • When you need a concise value-based mapping from an input.
  • When using pattern matching for cleaner and more readable code.
  • When you want to avoid fall-through bugs common in switch statements.
Comment
Article Tags:

Explore