2

Can I have a switch statement like this:

...

switch (temp)
{
case "NW" or "New":
temp = "new stuff"
break;
}

...

Tom Anderson
  • 10,807
  • 3
  • 46
  • 63
MrM
  • 21,709
  • 30
  • 113
  • 139

6 Answers6

16

No, but you can use (at least in Java)

switch (temp) {
    case "NW":
    case "New":
       temp="new stuff";
       break;
}
laginimaineb
  • 8,245
  • 1
  • 22
  • 14
10

Yes. This is how it is done.

switch (temp)
{
   case "NW":
   case "New":
     temp = "new stuff"
     break;
}

Actually, I answered this very same question before.

Community
  • 1
  • 1
Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
3

Try

switch (temp)
{
case "NW":
case "New":
temp = "new stuff"
break;
}
Brandon
  • 68,708
  • 30
  • 194
  • 223
3

Assuming C#, you want:

switch(temp)
{
    case "NW":
    case "New":
        temp = "new stuff";
        break;
}
Brian Genisio
  • 47,787
  • 16
  • 124
  • 167
2
switch (temp) {
    case "NW":
    case "New":
        temp = "new stuff"
        break;
    default:
        Console.WriteLine("Hello, World!");
        break;
}
jason
  • 236,483
  • 35
  • 423
  • 525
1

I know you asked about C#, and have good answers there, but just for perspective (and for anyone else reading that might find it useful), here's the VB answer:

Select Case temp
  Case "NW", "New"
    temp = "new stuff"
  Case Else
    'something else...
End Select

Notice that there's no "break"--VB does not drop through cases. On the other hand, you can have multiple match conditions on a single case.

Be care you DON'T do this

...
  Case "NW" Or "New"
...

What you have there is a single condition with a bitwise Or between the two terms....

RolandTumble
  • 4,633
  • 3
  • 32
  • 37