skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Switch expressions

C# 8

Code card: Switch expressions. Program output: *Cthulhu noises* / Purrr... / Woof!

A switch expression returns a value directly, with no case labels or temp variable. Pattern match with a switch expression: every arm returns a value, and _ catches the rest. It is available since C# 8. The key line is Species.Cat => "Purrr..." in switch.cs.

Did this tip save you some time? Consider buying me a coffee to fuel the next one.

Buy me a coffee
switch.cs
foreach (var species in Enum.GetValues<Species>())
{
Console.WriteLine(species switch
{
Species.Cat => "Purrr...",
Species.Dog => "Woof!",
_ => "*Cthulhu noises*",
});
}
enum Species { Unknown, Cat, Dog }
Output
$ dotnet run switch.cs
*Cthulhu noises*
Purrr...
Woof!