How to handle multiple values inside one case
? So if I want to execute the same action for value "first option"
and "second option"
?
Is this the right way?
switch(text)
{
case "first option":
{
}
case "second option":
{
string a="first or Second";
break;
}
}
Multiple conditions in CASE statementYou can evaluate multiple conditions in the CASE statement.
A switch statement using multiple value cases correspond to using more than one value in a single case. This is achieved by separating the multiple values in the case with a comma.
The switch can includes multiple cases where each case represents a particular value. Code under particular case will be executed when case value is equal to the return value of switch expression.
It's called 'multiple labels' in the documentation, which can be found in the C# documentation on MSDN.
A switch statement can include any number of switch sections, and each section can have one or more case labels (as shown in the string case labels example below). However, no two case labels may contain the same constant value.
Your altered code:
string a = null;
switch(text)
{
case "first option":
case "second option":
{
a = "first or Second";
break;
}
}
Note that I pulled the string a
out since else your a
will only be available inside the switch
.
It is possible
switch(i)
{
case 4:
case 5:
case 6:
{
//do someting
break;
}
}
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