views:

63

answers:

2

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

+7  A: 

.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'
}
Paul Ruane
I've been unable to upgrade unfortunately. Thanks for the quick answer
Marlon
A: 

I recently ran into this problem.

If you don't know what the type of the Enum is, then you can cast he Enum to an int and use the Enum static methods to parse an Enum field name into a value and use op_BitwiseAnd to compare the values.

I'll update this later with the code if you're interested, but am heading out the door now.