C# 8 switch expression with multiple cases with same result

huzle picture huzle · Jun 19, 2019 · Viewed 24.1k times · Source

How can a switch expression be written to support multiple cases returning the same result?

With C# prior to version 8, a switch may be written like so:

var switchValue = 3;
var resultText = string.Empty;
switch (switchValue)
{
    case 1:
    case 2:
    case 3:
        resultText = "one to three";
        break;
    case 4:
        resultText = "four";
        break;
    case 5:
        resultText = "five";
        break;
    default:
        resultText = "unkown";
        break;
}

When I am using the C# version 8, with the expression syntax, it's like so:

var switchValue = 3;
var resultText = switchValue switch
{
    1 => "one to three",
    2 => "one to three",
    3 => "one to three",
    4 => "four",
    5 => "five",
    _ => "unknown",
};

So my question is: How to turn the cases 1, 2 and 3 to just one switch-case-arm so the value doesn't need to be repeated?

Update per suggestion from "Rufus L":

For my given example, this works.

var switchValue = 3;
var resultText = switchValue switch
{
    var x when (x >= 1 && x <= 3) => "one to three",
    4 => "four",
    5 => "five",
    _ => "unknown",
};

But it's not exactly what I want to accomplish. This is still only one case (with a filter condition), not multiple cases yielding to the same right-hand result.

Answer

Rufus L picture Rufus L · Jun 20, 2019

I got around to installing it, but I have not found a way to specify multiple, separate case labels for a single switch section with the new syntax.

However, you can create a new variable that captures the value and then use a condition to represent the cases that should have the same result:

var resultText = switchValue switch
{
    var x when
        x == 1 ||
        x == 2 ||
        x == 3 => "one to three",
    4 => "four",
    5 => "five",
    _ => "unknown",
};

This is actually more concise if you have many cases to test, because you can test a range of values in one line:

var resultText = switchValue switch
{
    var x when x > 0 && x < 4 => "one to three",
    4 => "four",
    5 => "five",
    _ => "unknown",
};