Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 473
Marlon Avatar asked Oct 13 '10 22:10

Marlon


1 Answers

.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'
}
like image 162
Paul Ruane Avatar answered Oct 02 '22 18:10

Paul Ruane