Coder Perfect

Switch statement with several cases

Problem

Is there a way to descend through several case statements without having to say case value: over and over again?

This is how I know it works:

switch (value)
{
   case 1:
   case 2:
   case 3:
      // Do some stuff
      break;
   case 4:
   case 5:
   case 6:
      // Do some different stuff
      break;
   default:
       // Default stuff
      break;
}

However, I’d like to try something similar to this:

switch (value)
{
   case 1,2,3:
      // Do something
      break;
   case 4,5,6:
      // Do something
      break;
   default:
      // Do the Default
      break;
}

Is this grammar from a foreign language, or am I oblivious to something?

Asked by theo

Solution #1

I believe this has already been addressed. However, I believe that you may still combine the two alternatives in a more syntactically sound manner by doing:

switch (value)
{
    case 1: case 2: case 3:          
        // Do Something
        break;
    case 4: case 5: case 6: 
        // Do Something
        break;
    default:
        // Do Something
        break;
}

Answered by Carlos Quintanilla

Solution #2

The second technique you suggested has no syntax in C++ or C#.

Your first method is perfectly acceptable. If you have really large ranges, though, simply use a series of if statements.

Answered by Brian R. Bondy

Solution #3

Range-based switching is now possible with the switch statement in C# 7 (available by default in Visual Studio 2017/.NET Framework 4.6.2) and might help with the OP’s dilemma.

Example:

int i = 5;

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

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

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

// Output: I am between 4 and 6: 5

Notes:

Answered by Steve Gomez

Solution #4

This syntax comes from the Select…Case Statement in Visual Basic:

Dim number As Integer = 8
Select Case number
    Case 1 To 5
        Debug.WriteLine("Between 1 and 5, inclusive")
        ' The following is the only Case clause that evaluates to True.
    Case 6, 7, 8
        Debug.WriteLine("Between 6 and 8, inclusive")
    Case Is < 1
        Debug.WriteLine("Equal to 9 or 10")
    Case Else
        Debug.WriteLine("Not between 1 and 10, inclusive")
End Select

In C#, you can’t use this syntax. You must instead use the syntax from the first example.

Answered by Neal

Solution #5

You can omit the newline, which results in:

case 1: case 2: case 3:
   break;

However, I believe that is a poor style.

Answered by Allan Wind

Post is based on https://stackoverflow.com/questions/68578/multiple-cases-in-switch-statement