HasFlags always returns true for None (0) value in enum
There is already a plethora of answers describing WHY this happens, so I will just add that what you can do to get what you're looking for is to not use HasFlag
in that case, but instead do var hasNone = myAnimals == Animals.None
.
I personally really loathe extension methods, but it would be possible to put this in an extension on Enum
if you really value being able to just write myOptionEnum.HasNoFlags()
. I would just run with explicitly checking for the None
value in this special case though.
HasFlag
is effectively this:
HasFlag = (GivenFlag & Value) == GivenFlag;
//"Anything" AND 0 == 0 --> always true
I've come up against this before myself. It's by design in the .NET Framework:
If the underlying value of flag is zero, the method returns true. If this behavior is not desirable, you can use the Equals method to test for equality with zero and call HasFlag only if the underlying value of flag is non-zero, as the following example illustrates.
You can read a little more about this in the MSDN article here: http://msdn.microsoft.com/en-GB/library/system.enum.hasflag.aspx