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

c#, switch-statement

Solution

Original Answer for C# 7

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:`.

Updated examples for C# 9

switch(myValue)
{
    case <= 0:
        Console.WriteLine("Less than or equal to 0");
        break;
    case > 0 and <= 10:
        Console.WriteLine("More than 0 but less than or equal to 10");
        break;
    default:
        Console.WriteLine("More than 10");
        break;
}

or

var message = myValue switch
{
    <= 0 => "Less than or equal to 0",
    > 0 and <= 10 => "More than 0 but less than or equal to 10",
    _ => "More than 10"
};
Console.WriteLine(message);

Problem

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; } ```

Original source

Related problems