DEV Community

Miguel Teheran
Miguel Teheran

Posted on

C# 8 - switch expression

C# 8 has new interesting features. One of them that I like it's the new way to write a switch.

int intValueForSwitch = 0;
string state = "";

switch (intValueForSwitch)
{
    case 0:
      state = "Zero";
    break;
    case 1:
      state = "One";
    break;
    case 2:
      state = "Two";
    break;
    default:
      state = "No valid number";
    break;
}
Enter fullscreen mode Exit fullscreen mode

The code above is a special situation because we use the switch just to set the value to the state variable.
The idea is to avoid nested if and use a switch. the code is still long for this propose.

In C# 8 a new way for this case is available.

//switch as expression
int intValueForSwitch = 0;

var state = (intValueForSwitch) switch
{
    (0) => "Zero",
    (1) => "One",
    (2) => "Two",
     _ => "NO valid number"
};
Enter fullscreen mode Exit fullscreen mode

First, the variable doesn't need to be created before that means one line less. Using the arrow operator " => " we can return the string it depending on the state variable's value. Finally, we need to use underscore " _ " to set the default value when the variable doesn't accomplish for any case.

This feature allows us to reduce the code. In this case, for example, 17 lines are just 7 now.

You can try it out using Visual 2019!!

Take a look at all the feature's history in C# in the following repository:
https://github.com/Mteheran/CSharpVersionsDemos

Latest comments (1)

Collapse
 
bshinji profile image
πŸ…ΉπŸ†„πŸ…»πŸ…ΈπŸ…°πŸ…½ πŸ…°πŸ†„πŸ…ΆπŸ†„πŸ†‚πŸ†ƒπŸ…Ύ

It's just eyecandy, the compiler makes the same thing in backwards