25

Possible Duplicate:
Multiple Cases in Switch:

Is it possible to do a multiple constant-expression switch statement like

switch (i) {
   case "run","notrun", "runfaster": //Something like this.
      DoRun();
      break;
   case "save":
      DoSave();
      break;
   default:
      InvalidCommand(command);
      break;
   }
Community
  • 1
  • 1
Amra
  • 24,780
  • 27
  • 82
  • 92

1 Answers1

57

Yes, it is. You can use multiple case labels for the same section:

switch (i) 
{  
    case "run": 
    case "notrun":
    case "runfaster":   
        DoRun();  
        break;  
    case "save":  
        DoSave();  
        break;  
    default:  
        InvalidCommand(command);  
        break;  
}  
D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
  • 3
    I note that you are conceptualizing this as a C-style switch, where there is "fall through" and the gap between the labels can be empty. A better way to think about it in C# is that *each section has one or more labels* and *there is no fall through between sections*. – Eric Lippert Oct 01 '10 at 14:07
  • @Eric: You are right, that is a much cleaner perspective leaving no room for misinterpretation. The analogy of "fall-through" is a sticky one, a strong visualization, and hard to shake. – D'Arcy Rittich Oct 01 '10 at 14:15
  • 2
    Also, while we're being picky, case labels are "case labels", not "case statements". They are not statements; they are not legal *anywhere* that a statement is legal. – Eric Lippert Oct 01 '10 at 15:28