How add "or" in switch statements?
Asked Answered
A

7

162

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.

Ambulant answered 11/5, 2009 at 14:49 Comment(2)
What do you mean "it didn't work"? Does it give you syntax errors, or logical errors?Cervine
Starting with C# 9, this exact syntax is allowed.Sedentary
T
405

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

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

    case 7:
    case 12:
    ...
    break;
    ...
}
Transcendent answered 11/5, 2009 at 14:51 Comment(2)
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).Godless
This was exactly what I was looking for. Good job, your work is appreciated.Simulacrum
S
44

You do it by stacking case labels:

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

    case 7: 
    case 12:
    ...
    break;
    ...
}
Slowwitted answered 11/5, 2009 at 14:51 Comment(0)
J
27

You may do this as of C# 9.0:

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

    case 7 or 12:
        // ...
        break;
    // ...
}
Jo answered 11/11, 2020 at 20:21 Comment(1)
This is more readable then allowing it fall through, downside it's C# 9.0 up only as you pointed out.Christoffer
S
22
case 2:
case 5:
do something
break;
Selfcommand answered 11/5, 2009 at 14:51 Comment(0)
T
18

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... }

Tadashi answered 11/5, 2009 at 14:55 Comment(1)
Note that this is only true for empty cases. Cases with actual body do not automatically fall through.Selfcommand
B
7

Since C# 8 there are switch expressions that are better readable: no case, : and break;/return needed anymore. Combined with C# 9's logical patterns:

static string GetCalendarSeason(DateTime date) => date.Month switch
{
    3 or 4 or 5 => "spring",
    6 or 7 or 8 => "summer",
    9 or 10 or 11 => "autumn",
    12 or 1 or 2 => "winter",
    _ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
};

Limitation: with this syntax, at the right of the => you cannot use curly braces ({ and }) for statements.

Bisexual answered 12/5, 2022 at 11:29 Comment(0)
I
6

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.");
   }
}
Internationalist answered 11/5, 2009 at 14:59 Comment(3)
-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.Codding
Usefull answer as example of "goto case".Chantellechanter
I hate goto statements what is this 1992?Cicily

© 2022 - 2024 — McMap. All rights reserved.