3

I know that using multiple values in a switch case should mean you ought to be using an if-else setup but this is more of a theory question than a practicality.

My question is thus:

switch(x){
    case 4:
        break;
    case 5 || 6:
        break;
}

The above 5 || 6 illustrates the case firing on either x being 5 or 6.

Is this at all possible?

Edit: This is a question as to the design of the switch decision making rather than using fall-throughs.

2
  • 3
    more like: ``` case 5: case 6: break; ``` Commented May 1, 2019 at 8:41
  • Yes Commented May 1, 2019 at 8:42

2 Answers 2

8

You can just fall through like this to match 5 or 6:

switch(x){
    case 4:
        break;
    case 5:
    case 6:
        // do something for 5 or 6
        break;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Of course you can, with help of Pattern matching in C#7
I know this not the elegant way, but its what OP asks for

switch(x){
    case var rule when x == 4:
        //do your things
        break;
    case var rule when x == 5 || x == 6:
        //do your other things
        break;
}

2 Comments

“of course you can” — except that, until very recently, you couldn’t.
@KonradRudolph, yeah your right, rest of sentence almost implied that :).