Search code examples
c#enumsenum-flags

How to iterate over values of an Enum having flags?


If I have a variable holding a flags enum, can I somehow iterate over the single-bit values in that specific variable? Or do I have to use Enum.GetValues to iterate over the entire enum and check which ones are set?


Solution

  • Coming back at this a few years later, with a bit more experience, my ultimate answer for single-bit values only, moving from lowest bit to highest bit, is a slight variant of Jeff Mercado's inner routine:

    public static IEnumerable<Enum> GetUniqueFlags(this Enum flags)
    {
        ulong flag = 1;
        foreach (var value in Enum.GetValues(flags.GetType()).Cast<Enum>())
        {
            ulong bits = Convert.ToUInt64(value);
            while (flag < bits)
            {
                flag <<= 1;
            }
    
            if (flag == bits && flags.HasFlag(value))
            {
                yield return value;
            }
        }
    }
    

    It seems to work, and despite my objections of some years ago, I use HasFlag here, since it's far more legible than using bitwise comparisons and the speed difference is insignificant for anything I'll be doing. (It's entirely possible they've improved the speed of HasFlags since then anyway, for all I know...I haven't tested.)