Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle multiple values inside one case? [closed]

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;
    }
}
like image 645
CodeBreaker Avatar asked Jan 14 '15 13:01

CodeBreaker


People also ask

Can you have multiple conditions in a case statement?

Multiple conditions in CASE statementYou can evaluate multiple conditions in the CASE statement.

Can a switch case have multiple values?

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.

Which expression can handle multiple cases?

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.


2 Answers

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.

like image 153
Patrick Hofman Avatar answered Sep 21 '22 16:09

Patrick Hofman


It is possible

switch(i)
                {
                    case 4:
                    case 5:
                    case 6: 
                        {
                            //do someting
                            break; 
                        }
                }
like image 28
Giorgi Nakeuri Avatar answered Sep 19 '22 16:09

Giorgi Nakeuri