Search code examples
c#enum-flags

Testing for multiple flag values


I have this flag enumeration:

public enum AssignmentType
{
    None = 0,
    Attendant = 1,
    ConductorCBS = 2,
    ReaderCBS = 4,
    Chairman = 8,
    Mike = 16,
    PlatformAttendant = 32,
    Prayer = 64,
    OCLM = 128,
    Sound = 256,
    Student = 512,
    Custom = 1024,
    Demonstration = 2048,
    Assistant = 4096
}

I am now wanting to test my variable for a certain flag condition.

I want to identify my variable is only any combination of:

  • None
  • Student
  • Assistant
  • Demonstration

So if it has any of the other enumeration values the variable would not satisfy the test.

At first I started with this:

bool bIsPersonnel = true;

if (_Assignments == AssignmentType.None ||
    _Assignments == AssignmentType.Demonstration || 
    _Assignments == AssignmentType.Student ||
    _Assignments == AssignmentType.Assistant ||
    _Assignments == (AssignmentType.Demonstration | AssignmentType.Student))
{
    bIsPersonnel = false;
}

But I quickly realised the multiple choices there are.

Is there a simpler way?

I can't see how to suggested answer helps. I guess it is easiest to do my test in reverse. Just test if it has any of the other flags then I know it is personnel!


Solution

  • You can apply a mask with the ~ bitwise negation operator to find all the invalid flags, and check whether any have been applied.

    var valid = AssignmentType.Student | AssignmentType.Assistant | AssignmentType.Demonstration;
    var invalid = ~valid; // Everything that isn't valid
    
    if ((_Assignments & invalid) != 0)
    {
        // There was at least one invalid flag, handle it appropriately
    }
    

    Or to check whether it's valid:

    if ((_Assignment & invalid) == 0)
    {
        // There are no invalid flags, handle it appropriately
    }
    

    Or if you're just after setting a single boolean flag, you don't need an if statement at all:

    bool isPersonnel = ((assignment & invalid) != 0);