Search code examples
c#enumsflags

Enum.HasFlag, why no Enum.SetFlag?


I have to build an extension method for each flag type I declare, like so:

public static EventMessageScope SetFlag(this EventMessageScope flags, 
    EventMessageScope flag, bool value)
{
    if (value)
        flags |= flag;
    else
        flags &= ~flag;

    return flags;
}

Why isn't there an Enum.SetFlag like there is an Enum.HasFlag?

Also, why does this not work always?

public static bool Get(this EventMessageScope flags, EventMessageScope flag)
{
    return ((flags & flag) != 0);
}

For example, if I have:

var flag = EventMessageScope.Private;

And check it like:

if(flag.Get(EventMessageScope.Public))

Where EventMessageScope.Public really is EventMessageScope.Private | EventMessageScope.PublicOnly, it returns true.

When it's not, because Private is not public, it's just half public.

The same goes for:

if(flag.Get(EventMessageScope.None))

Which returns false, except the scope is actually None (0x0), when it should always return true?


Solution

  • The & operator will give you the same answer with a & b as it will with b & a, so

    (EventMessaageScope.Private).Get(EventMessageScope.Private | EventMessageScope.PublicOnly)

    is the same as writing

    (EventMessageScope.Private | EventMessageScope.PublicOnly).Get(EventMessaageScope.Private)

    If you just want to know if the value is the same as EventMessaageScope.Public, then just use equals:

    EventMessageScope.Private == EventMessageScope.Public

    Your method will always return false for (EventMessageScope.None).Get(EventMessaageScope.None) because None == 0 and it only returns true when the result of the AND operation is not zero. 0 & 0 == 0.