Search code examples
c#switch-statementor-operator

'||' operators to be used between two enums in a switch statement


I want to check if a function returns either of two enum values, each of the same enumeration type.

For simplicity's sake, I attempted to create a case as follows:

case EnumerationTypeExample.TypeA || EnumerationTypeExample.TypeB:

Unfortunately, this does not please C#, which says I cannot use an '||' operator despite them being of the same type; strange. Might there be a way this could be done otherwise? An if statement perhaps might work and I may retreat to that, however, I would much rather use a switch statement if possible.


Solution

  • A case statement must be constants, not a computation. However you can use fall through in this case:

    switch (something)
    {
        case EnumerationTypeExample.TypeA:
        case EnumerationTypeExample.TypeB:
        {
            DoSomething();   
            break;  
        }
    }
    

    Now the code will run in both situations.