Switch expressions
On trails:CSMODERNstep 3/7
A switch expression (C# 8.0+) is a more concise form of the switch statement that is an expression, and returns a value. It often uses pattern matchingPattern matchingTest the shape of a value and pull data out of it in one step.Opens in a new tab.
The switch is on line 1, and the whole thing is an expression, so it returns a value. Line 4 combines two values with or. Line 5 is the discard _, the catch-all.
C#
string GetDayType(DayOfWeek day) => day switch{ DayOfWeek.Monday => "Start of work week", DayOfWeek.Saturday or DayOfWeek.Sunday => "Weekend", _ => "Midweek"};Sources
- milanm/csharp-cheatsheet, GitHub · accessed May 16, 2025