Switch Expressions in C# 8.0

Programming C#

The new C# 8.0 switch expressions are a very convenient way to map information in a very compact fashion.

One of the most awaited features of .NET Core 3.0 is the latest version of C#. In addition to some internal improvements to the compiler, C# ver 8.0 brings a few interesting new features to the language like f.e. Tupple Patterns and the Switch Expressions.

Switch expressions are a very convenient way to map information in a compact fashion. Take a look at the following switch statement:

public int Calculate(string operation, int operand1, int operand2) {
int result;

switch (operation) {
case "+":
result = operand1 + operand2;
break;
case "-":
result = operand1 - operand2;
break;
case "*":
result = operand1 * operand2;
break;
case "/":
result = operand1 / operand2;
break;
default:
throw new ArgumentException($ "The operation {operation} is invalid!");
}

return result;
}

You can rewrite this method in a more compact way as shown in the following code:

public int Calculate(string operation, int operand1, int operand2) {
var result = operation switch
{
"+" => operand1 + operand2,
"-" => operand1 - operand2,
"*" => operand1 * operand2,
"/" => operand1 / operand2,
_ =>
throw new ArgumentException($ "The operation {operation} is invalid!"),
};

return result;
}

As you can see, the switch keyword acts as an operator between the variable to check (operation in the example) and the map of expressions to evaluate. The resulting code is much more readable since you are now able to catch at a glance which expression matches the operation.