C# 8 switch expression with multiple cases with same result

前端 未结 4 1365
终归单人心
终归单人心 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:16

    Sadly, this appears to be a shortcoming in the switch-expression syntax, relative to the switch-statement syntax. As other posters have suggested, the rather clumsy var syntax is your only real option.

    So you might have been hoping you could write:

    switchValue switch {
        Type1 t1:
        Type2 t2:
        Type3 t3 => ResultA, // where the ResultX variables are placeholders for expressions.
        Type4 t4 => ResultB,
        Type5 t5 => ResultC
    };
    

    Instead you will need to write the rather awkward code below, with typename sprayed about:

    switchValue switch {
        var x when x is Type1 || x is Type2 || x is Type 3 => ResultA,
        Type4 t4 => ResultB,
        Type5 t5 => ResultC
    };
    

    In such a simple example, you can probably live with this awkwardness. But more complicated example are much less liveable with. In fact my examples are actually a simplification of an example drawn from our own code base, where I was hoping to convert a switch-statement, with roughly six outcomes but over a dozen type-cases, into a switch-expression. And the result was clearly less readable than the switch-statement.

    My view is that if the switch-expression needs shared outcomes and is more than a few lines long, then you are better off sticking to a switch-statement. Boo! It's more verbose but probably a kindness to your teammates.

    ResultType tmp;
    switch (switchValue) {
        case Type1 t1:
        case Type2 t2:
        case Type3 t3:
            tmp = ResultA;
            break;
        case Type4 t4:
            tmp = ResultB;
            break;
        case Type5 t5:
            tmp = ResultC;
            break;
    };
    return tmp;
    

提交回复
热议问题