views:

129

answers:

1

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;
   }
+12  A: 

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;  
}  
RedFilter
@RedFilter: I believe you have to put colons after each case statement. case "run":, case "notrun": and so on.
DOK
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
@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.
RedFilter
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
@Eric: Noted, I have updated my answer accordingly.
RedFilter