Switch Expression in C# 8.0
The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. So, with switch statement you always use some repetitive case and break keywords and also use default statement as shown in the below example:
This is the basic introduction of the switch statement. Now coming to the main topic, as we know that Microsoft has released the latest version of C# that is C# 8.0. In C# 8.0, the developers made some improvements in the switch statement and after improvements, the switch statement is converted into switch expression and the improvements are as follows:
- The variable used in switch expression is now coming before the switch keyword.
- Colon (:) and case keyword are replaced with arrows (=>). Which makes the code more compact and readable.
- The default case is now replaced with a discard(_).
- And the body of the switch is expression, not a statement.
Now, we modify the above example, according to the new improvements. These new improvements make our program more compact and easy to read as compared to the traditional method.
Favorite Language: Java