How to handle multiple values inside one case?

CodeBreaker picture CodeBreaker · Jan 14, 2015 · Viewed 11.7k times · Source

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;
    }
}

Answer

Patrick Hofman picture Patrick Hofman · Jan 14, 2015

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.