tags:

views:

388

answers:

5

Hello,

This is what I want to do:

switch(myvar)
{
    case: 2 or 5:
    ...
    break;

    case: 7 or 12:
    ...
    break;
    ...
}

I tried with "case: 2 || 5" ,but it didn't work.

The purpose is to not write same code for different values.

+29  A: 

By stacking each switch case, you achieve the OR condition.

switch(myvar)
{
    case 2:
    case 5:
    ...
    break;

    case 7:
    case 12:
    ...
    break;
    ...
}
Jose Basilio
+1 you beat me to it!
Richard Ev
seconds in it, but to the victor: the spoils ;-p
Marc Gravell
Joel, it doesn't support fall through but it DOES support stacking (e.g., an empty case 2 in this answer executes the case 5 section).
paxdiablo
+5  A: 
case 2:
case 5:
do something
break;
On Freund
+9  A: 

You do it by stacking case labels:

switch(myvar)
{
    case 2:
    case 5:
    ...
    break;

    case 7: 
    case 12:
    ...
    break;
    ...
}
Dave Webb
+4  A: 

Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write

switch(myvar)
{
   case 2:
   case 5:
   {
      //your code
   break;
   }

// etc... }

AnnaR
Note that this is only true for empty cases. Cases with actual body do not automatically fall through.
On Freund
+1  A: 

The example for switch statement shows that you can't stack non-empty cases, but should use gotos:

// statements_switch.cs
using System;
class SwitchTest 
{
   public static void Main()  
   {
      Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large"); 
      Console.Write("Please enter your selection: "); 
      string s = Console.ReadLine(); 
      int n = int.Parse(s);
      int cost = 0;
      switch(n)       
      {         
         case 1:   
            cost += 25;
            break;                  
         case 2:            
            cost += 25;
            goto case 1;           
         case 3:            
            cost += 50;
            goto case 1;             
         default:            
            Console.WriteLine("Invalid selection. Please select 1, 2, or3.");            
            break;      
       }
       if (cost != 0)
          Console.WriteLine("Please insert {0} cents.", cost);
       Console.WriteLine("Thank you for your business.");
   }
}
gimel
Nice spaghetti code +1
ichiban
Verbatim copy from the ref document.
gimel
-1 The msdn link has a stacked example further down the page. At any rate, stacked cases work, especially in this question where the stated purpose is to not write duplicate code as done in your case 1 and 2.
Gary.Ray