Search code examples
c#genericsenum-flags

C# extension method to check if an enumeration has a flag set


I want to make an extension method to check if an enumeration has a flag.

DaysOfWeek workDays = DaysOfWeek.Monday | DaysOfWeek.Tuesday | DaysOfWeek.Wednesday;
// instead of this:
if ((workDays & DaysOfWeek.Monday) == DaysOfWeek.Monday)
   ...

// I want this:
if (workDays.ContainsFlag(DaysOfWeek.Monday))
   ...

How can I accomplish this? (If there is a class that already does this then I would appreciate an explanation to how this can be coded; I've been messing around with this method far too long!)

thanks in advance


Solution

  • .NET 4 already includes this funcitonality so, if possible, upgrade.

    days.HasFlag(DaysOfWeek.Monday);
    

    If it's not possible to upgrade, here is the implementation of said method:

    public bool HasFlag(Enum flag)
    {
        if (!this.GetType().IsEquivalentTo(flag.GetType())) {
            throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType())); 
        }
    
        ulong uFlag = ToUInt64(flag.GetValue()); 
        ulong uThis = ToUInt64(GetValue());
        return ((uThis & uFlag) == uFlag); 
    }
    

    You could easily build the equivalent extension method:

    public static bool HasFlag(this Enum @this, Enum flag)
    {
        // as above, but with '@this' substituted for 'this'
    }