1

Recently as of C# 8.0 they introduced a new switch case that is rapidly replacing our nested ternary if statements in our code base as such:

var number = 1;
var evenness = number switch 
{ 
    1 => "odd", 
    2 => "even", 
    3 => "odd", 
    4 => "even",
    _=>"out of range" 
};

And I freaking love it! It's really nice, clean and succinct.

However, this could be improved with the following old style switch statement from this question Multiple cases in switch statement

string eventness2;
switch (number)
{
    case 1: case 3:
        eventness2 = "odd";
        break;
    case 2: case 4:
        eventness2 = "event";
        break;
    default:
        eventness2 = "out of range";
        break;
}

My question is, is there any way to support multiple cases within a one line switch statement similar to this invalid syntax

var evenness = number switch { 1,3 => "odd", 2,4 => "even",_=>"out of range";
Magnetron
  • 7,495
  • 1
  • 25
  • 41
apinostomberry
  • 139
  • 1
  • 11

1 Answers1

3

Of course, using pattern matching:

var evenness = number switch { 1 or 3 => "odd", 2 or 4 => "even", _ => "out of range" };
Blindy
  • 65,249
  • 10
  • 91
  • 131