Why does MSDN state that HasFlag is *designed* to work with FlagsAttribute?

411 Views Asked by At

The question What does the [Flags] Enum Attribute mean in C#? doesn't ask what I'm asking and also doesn't answer it. If there is such answer in that question, please, state which one (link) in the comments rather than mindlessly and erroneously flagging as a duplicate.


There is this note on MSDN's HasFlag documentation:

The HasFlag method is designed to be used with enumeration types that are marked with the FlagsAttribute attribute and can be used to determine whether multiple bit fields are set. For enumeration types that are not marked with the FlagsAttribute attribute, call either the Equals method or the CompareTo method.

But I've tested it and the method worked fine despite the enum being marked or not with the FlagsAttribute.

Maybe the note on the docs is just an attempt to enforce some sort of *good practice* by using the attribute (and it doesn't matter in the end at all)?


I took a peek here and it indeed seems that there is no restriction on the enum whatsoever (it's just a simple bitwise AND):

public Boolean 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);
}

So, why on earth does it say that it's *designed* to work with the FlagsAttribute when in reality it doesn't rely on it?

1

There are 1 best solutions below

0
On

HasFlags only makes sense on Flags enums. You don't have to declare an enum as Flags but that is recommended. It is documentation, and it tuns on flags ToString formatting.

MSDN recommends that you either create a flags enum, mark it Flags and use HasFlags, or do none of that. Do not mix.

That's all this sentence is trying to convey. It pushes you to best-practices. Ideally, there would be a link to a page explaining flags but that is not how MSDN is typically handled (alas). They mostly tell you what you can do, not what you should do.