C# 8 - switch expression

mteheran profile image Miguel Teheran ・1 min read

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";
    case 1:
      state = "One";
    case 2:
      state = "Two";
      state = "No valid number";

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"

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:


Editor guide
bshinji profile image