How add "or" in switch statements?
C#Switch StatementC# Problem Overview
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.
C# Solutions
Solution 1 - C#
By stacking each switch case, you achieve the OR condition.
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
Solution 2 - C#
You do it by stacking case labels:
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
Solution 3 - C#
case 2:
case 5:
do something
break;
Solution 4 - C#
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... }
Solution 5 - C#
switch(myvar)
{
case 2 or 5:
// ...
break;
case 7 or 12:
// ...
break;
// ...
}
Solution 6 - C#
The example for [switch statement][1] 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.");
}
}
[1]: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch "The documentation for switch statements"
Solution 7 - C#
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.