C# 8 Switch Expression

In C# 8.0 pattern matching enhancements are used to improve upon swtich statements. In earlier version classic switch statements had case blocks, in C# 8.0 switch now has expressions, thus adding new capabilities to it.

Let’s look at an example of C# 8 switch expression:

Before C# 8.0 switch statement to get discount based on customer type and order value:

C# 8.0 switch expression based solution for this :

Tuple based swtich expressions are also supported in C# 8.0 . In the above example, let’s add additional 5 discount on first order by any type of customer.

In addition to this now we can directly pass any object and switch expression can evaluate on it’s property directly using property pattern.

  If all of the switch cases are not handled then compiler gives a warning ‘The switch expression does no handle all possible inputs’ and it throws an exception when none of the cases handle the input – System.Runtime.CompilerServices.SwitchExpressionException: Non-exhaustive switch expression failed to match its input.
Unmatched value was Customer. .