C# 8 switch expression with multiple cases with same result

C# 9 supports the following:

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

Alternatively:

var switchValue = 3;
var resultText = switchValue switch
{
    >= 1 and <= 3 => "one, two, or three",
    4 => "four",
    5 => "five",
    _ => "unknown",
};

Source


For older versions of C#, I use the following extension method:

public static bool In<T>(this T val, params T[] vals) => vals.Contains(val);

like this:

var switchValue = 3;
var resultText = switchValue switch
{
    var x when x.In(1, 2, 3) => "one, two, or three",
    4 => "four",
    5 => "five",
    _ => "unknown",
};

It’s a little more concise than when x == 1 || x == 2 || x == 3 and has a more natural ordering than when new [] {1, 2, 3}.Contains(x).

Leave a Comment