tags:

views:

415

answers:

6

Can I have a switch statement like this:

...

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

...

+10  A: 

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.

Jose Basilio
Thanks for the help
+3  A: 

Try

switch (temp)
{
case "NW":
case "New":
temp = "new stuff"
break;
}
Brandon
Thanks for the help
+3  A: 

Assuming C#, you want:

switch(temp)
{
    case "NW":
    case "New":
        temp = "new stuff";
        break;
}
Brian Genisio
Thanks for the help
+11  A: 

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

switch (temp) {
    case "NW":
    case "New":
       temp="new stuff";
       break;
}
laginimaineb
Thanks for the help
C# doesn't allow fall-through case statements. Might be worth adding it. Your answer IS perfect for Java though :D (+1)
@devinb - sorry, I don't get what that means. Could you elaborate please?
laginimaineb
C# does allow fall through in this one special case were there is nothing in a particular case. So the above is valid C#
Martin York
@Martin, you are correct. I'd edit my comment but I can't. Thanks for pointing it out :)
+2  A: 
switch (temp) {
    case "NW":
    case "New":
        temp = "new stuff"
        break;
    default:
        Console.WriteLine("Hello, World!");
        break;
}
Jason
+1  A: 

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