This is what I want to do:
switch(myvar)
{
case: 2 or 5:
...
break;
case: 7 or 12:
...
break;
...
}
I tried wi
You may do this as of C# 9.0:
switch(myvar)
{
case 2 or 5:
// ...
break;
case 7 or 12:
// ...
break;
// ...
}
You do it by stacking case labels:
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
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... }
The example for switch statement shows that you can't stack non-empty case
s, but should use goto
s:
// 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.");
}
}
By stacking each switch case, you achieve the OR condition.
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
case 2:
case 5:
do something
break;