Tip #010
Switch expressions
About this tip
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.
Learn more
Did this tip save you some time? Consider buying me a coffee to fuel the next one.
Buy me a coffeeCode
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!