How to iterate over values of an Enum having flags?

user502255 picture user502255 · Nov 13, 2010 · Viewed 66k times · Source

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?

Answer

Greg picture Greg · Nov 13, 2010
static IEnumerable<Enum> GetFlags(Enum input)
{
    foreach (Enum value in Enum.GetValues(input.GetType()))
        if (input.HasFlag(value))
            yield return value;
}