Answer 5562ce6c9113cb40db0002aaYou can't use “||” in case names. But you can use multiple case names without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a “break”.
The switch-case construct is pretty similar to an if-else statement, you can use the OR operator in an if however.
The logical OR operator (||) will not work in a switch case as one might think, only the first argument will be considered at execution time.
If you are eager to know how to use an OR condition in a Ruby switch case: So, in a case statement, a , is the equivalent of || in an if statement.
By stacking each switch case, you achieve the OR condition.
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
You do it by stacking case labels:
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
case 2:
case 5:
do something
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... }
You may do this as of C# 9.0:
switch(myvar)
{
case 2 or 5:
// ...
break;
case 7 or 12:
// ...
break;
// ...
}
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.");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With