Search code examples
c#enumsenum-flags

Is there a way to tell if an enum has exactly one, multiple or no flags set?


I have an enum defined like that:

[Flags]
public enum Orientation
{
    North = 1,
    North_East = 2,
    East = 4,
    South_East = 8,
    South = 16,
    South_West = 32,
    West = 64,
    North_West = 128
}

Is there a generic way to tell if exactly one flag is set, multiple or none? I don't care for what the value of the enum is, I just want to know how many flags are set.

This is not a duplicate for counting the number of bits. If I initialize the enum like this and count the number of bits I get 10. But the number of set flags would be 8.

GeographicOrientation go = (GeographicOrientation) 1023;

Solution

  • you can use this code :

    var item = Orientation.North | Orientation.South;
    int i = 0;
    foreach (Orientation e in Enum.GetValues(typeof(Orientation)))
        if(item.HasFlag(e))
            i++;
    
    Console.WriteLine(i);