6

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;
    }
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
CodeBreaker
  • 73
  • 1
  • 1
  • 7
  • See [this](http://csharp.net-tutorials.com/basics/switch-statement/) article for some guidelines. The main thing that jumps out at me is that the first case is missing a `break` statement – Mord Zuber Jan 14 '15 at 13:08
  • 2
    Friendly suggestion - get used to [documentation](http://msdn.microsoft.com/en-us/library/06tc147t.aspx) – Renatas M. Jan 14 '15 at 13:13
  • @Max It's wanted, so the following case is executed. – Omar Jan 14 '15 at 13:18
  • 1
    Thanks @Max the article was helpful. i deliberately escaped a break to cover cases and let execution continue.The brackets after the first case were the root cause of my problem. – CodeBreaker Jan 14 '15 at 13:19
  • Duplicate of [Multiple Cases in Switch](http://stackoverflow.com/questions/68578/multiple-cases-in-switch). – Omar Jan 14 '15 at 13:21

3 Answers3

19

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.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
3

It is possible

switch(i)
                {
                    case 4:
                    case 5:
                    case 6: 
                        {
                            //do someting
                            break; 
                        }
                }
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
1

You may be better off using just an if statement if you want to be able to treat both together and separate as distinct cases:

if (first && second)
{
    Console.WriteLine("first and second");
}
else if (first)
{
    Console.WriteLine("first only");
}
else if (second)
{
    Console.WriteLine("second only");
}
dav_i
  • 27,509
  • 17
  • 104
  • 136