In the first part of this series on what was introduced in C# 8, we’re going to take a look at switch expressions.
Switch expressions allow you to write fewer lines of code when making use of switch statements. This is useful if you have a switch statement that sets/returns a value based on the input.
Prior to C# 8, the following code could be used to convert an int to its string equivalent:
word = "one";
word = "two";
word = "three";
throw new ArgumentOutOfRangeException(nameof(number));
In the preceding code if the input int number is not 1,2, or 3 an exception is thrown, otherwise the variable word is set to the string representation “one”, “two”, or “three”.
From C# 8 we could instead use a switch expression. A switch expression returns a value, this means we can return the string into the word variable as follows:
string word = number switch
1 => "one",
2 => "two",
3 => "three",
_ => throw new ArgumentOutOfRangeException(nameof(number))
Compare this version with first version and you can see we have a lot less code, we don’t have all the repetitive case and breaks.
Also notice that the default block has been replaced with an expression that throws the exception. Also notice that the code makes use of a discard _ as we don’t care about the value. (Discards are “placeholder variables that are intentionally unused in application code” (MS)).
If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.