Switch case: can I use a range instead of a one number

user3022162 picture user3022162 · Nov 22, 2013 · Viewed 109.4k times · Source

I want to use switch, but I have many cases, is there any shortcut? So far the only solution I know and tried is:

switch (number)
{
case 1: something; break;
case 2: other thing; break;
...
case 9: .........; break;
}

What I hope I'm able to do is something like:

switch (number)
{
case (1 to 4): do the same for all of them; break;
case (5 to 9): again, same thing for these numbers; break;
}

Answer

Steve Gomez picture Steve Gomez · May 19, 2017

A bit late to the game for this question, but in recent changes introduced in C# 7 (Available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the switch statement.

Example:

int i = 63;

switch (i)
{
    case int n when (n >= 100):
        Console.WriteLine($"I am 100 or above: {n}");
        break;

    case int n when (n < 100 && n >= 50 ):
        Console.WriteLine($"I am between 99 and 50: {n}");
        break;

    case int n when (n < 50):
        Console.WriteLine($"I am less than 50: {n}");
        break;
}

Notes:

  • The parentheses ( and ) are not required in the when condition, but are used in this example to highlight the comparison(s).
  • var may also be used in lieu of int. For example: case var n when n >= 100:.