HasFlags always returns true for None (0) value in enum

Henrik Söderlund picture Henrik Söderlund · Mar 15, 2013 · Viewed 8.7k times · Source

This is the enum definition:

[Flags]
enum Animals
{
    None = 0,
    Dog = 1,
    Cat = 2,
    Horse = 4,
    Zebra = 8,
}

Now, given the following code, why does the HasFlag method return true for the value Animals.None?

Animals myAnimals = Animals.Dog | Animals.Horse;

var hasNone = myAnimals.HasFlag(Animals.None);    //true! Why?
var hasCat = myAnimals.HasFlag(Animals.Cat);      //false
var hasDog = myAnimals.HasFlag(Animals.Dog);      //true
var hasHorse = myAnimals.HasFlag(Animals.Horse);  //true
var hasZebra = myAnimals.HasFlag(Animals.Zebra);  //false

Answer

Austin Salonen picture Austin Salonen · Mar 15, 2013

HasFlag is effectively this:

HasFlag = (GivenFlag & Value) == GivenFlag;

//"Anything" AND 0 == 0  --> always true