C# 8 switch expression with multiple cases with same result

前端 未结 4 1353
终归单人心
终归单人心 2020-12-05 12:46

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:



        
4条回答
  •  死守一世寂寞
    2020-12-05 13:09

    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(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).

提交回复
热议问题