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);
}
HasFlags
only makes sense onFlags
enums. You don't have to declare an enum asFlags
but that is recommended. It is documentation, and it tuns on flagsToString
formatting.MSDN recommends that you either create a flags enum, mark it
Flags
and useHasFlags
, 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.