Introduced in C# 8.0, switch expressions transform switch statements into expressions that return values directly. They support pattern matching to enable more powerful conditional logic and dramatically reduce branching boilerplate, making code more declarative and easier to reason about.
Why it matters
Switch expressions eliminate intermediate variables and excessive branching code. They integrate seamlessly with C# pattern matching, enabling elegant handling of complex conditions. This is particularly valuable in domain logic, DTOs, and state machines where concise, maintainable expression-based decisions improve code quality and reduce cognitive load.
Cautions
While switch expressions are powerful, they can become hard to read when patterns become too complex or deeply nested. For simple two-branch conditions, ternary operators may remain more appropriate. Also note that switch expressions require exhaustive pattern coverage or an explicit discard pattern (_) to compile, which differs from statement-based switches.
Basic switch expression
Switch expressions provide a concise, expression-based alternative to traditional switch statements, reducing boilerplate and improving readability.
Valid since C# 8.0
// Traditional switch statement
string GetDayTypeOld(DayOfWeek day)
{
switch (day)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
return "Weekend";
default:
return "Weekday";
}
}
// Switch expression (C# 8.0)
string GetDayType(DayOfWeek day) =>
day switch
{
DayOfWeek.Saturday or DayOfWeek.Sunday => "Weekend",
_ => "Weekday"
};
Console.WriteLine(GetDayType(DayOfWeek.Monday)); // "Weekday"
Console.WriteLine(GetDayType(DayOfWeek.Saturday)); // "Weekend"
Switch expressions with patterns
Combine switch expressions with C# pattern matching for powerful, declarative logic without traditional statement syntax.
Valid since C# 8.0
using System;
// Pattern matching in switch expressions
public class Animal { }
public class Dog : Animal { public string Breed { get; set; } = string.Empty; }
public class Cat : Animal { public string Color { get; set; } = string.Empty; }
public static class Program
{
private static string DescribeAnimal(Animal animal) =>
animal switch
{
Dog { Breed: "Labrador" } => "Friendly Labrador",
Dog d => $"Dog of breed {d.Breed}",
Cat { Color: "Orange" } => "Orange tabby cat",
Cat => "A cat",
_ => "Unknown animal"
};
// Using guards (when clauses)
private static int Classify(int number) =>
number switch
{
< 0 => -1,
0 => 0,
> 0 and < 10 => 1,
>= 10 and < 100 => 2,
_ => 3
};
public static void Main()
{
var dog = new Dog { Breed = "Labrador" };
Console.WriteLine(DescribeAnimal(dog)); // "Friendly Labrador"
Console.WriteLine(Classify(42)); // 2
}
}