C# Switch Statements — Traditional vs. Expressions
Microsoft introduced a more concise and readable syntax for switch expression in C# 8.0, enhancing code clarity and efficiency. In this post, I’d like to compare the new expression syntax to the traditional version and discuss what sets them apart.
Why The New Syntax is Called Switch Expression?
The name “switch expression” shows that the new switch is meant to give a result directly, instead of doing multiple steps. This makes it fit better with functional programming principles and helps create shorter and clearer code.
Pros of the new syntax:
- Makes code look cleaner and simpler to understand
- The compiler warns about missing cases
- Supports complex and expressive matching
Cons of the new syntax:
- In some cases, it may not be suitable if you need to perform multiple actions
Syntax differences
First, let’s take a look at the syntax difference and move from there. input
is the variable that we are doing the switch operation on. a
and b
are our possible matches and the rest are simply the syntax for the switch