Ivan Prodanov Ivan Prodanov - 2 months ago 8
C# Question

How add "or" in switch statements?

This is what I want to do:

switch(myvar)
{
case: 2 or 5:
...
break;

case: 7 or 12:
...
break;
...
}


I tried with "case: 2 || 5" ,but it didn't work.

The purpose is to not write same code for different values.

Answer

By stacking each switch case, you achieve the OR condition.

switch(myvar)
{
    case 2:
    case 5:
    ...
    break;

    case 7:
    case 12:
    ...
    break;
    ...
}
Comments