How to use Switch Expressions in C# 8

If you've been in the development game for a while, you're no stranger to switch statements. I do have quite a few followers who are noobs though, so I'll give a quick breakdown using a definition by GeeksforGeeks

Switch case statements are a substitute for long if statements that compare a variable to several integral values 

  • The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
  • Switch is a control statement that allows a value to change control of execution.

Ok, now that we're all on the same page, let's have a look at what switch statements looked like prior to C#8. The following code simply converts an int to its string equivalent:

string word;
switch (number)
    case 1:
        word = "one";
    case 2:
        word = "two";
    case 3:
        word = "three";
        throw new ArgumentOutOfRangeException(nameof(number));                   
Note: Here if the input number is not 1,2, or 3 we throw an exception. Otherwise the variable word is set to "one", "two", or "three".
In C#8 we could make this code much simpler using a switch expression. Let me show you how:
string word = number switch
    1 => "one",
    2 => "two",
    3 => "three",
    _ => throw new ArgumentOutOfRangeException(nameof(number))
See that? Much cleaner, right? 
Notice how the default block has been replaced with an expression that throws the exception, and how we were able to get rid of all the repetitive cases and breaks.  Also, notice that this code makes use of a discard variable _ , which was introduced in C# 7. Discards are essentially unassigned variables that don't have value. They communicate that you intend to ignore the result of an expression.

Leave a Comment

Close Bitnami banner