Search code examples
c#enumsenum-flags

How can I get a collection of set bits from an instance of a flags enum?


The Enum class has the following useful function:

public static Array GetValues(Type enumType);

How could I write something similar to give me a collection of all an enum instance's set bits? With a signature like:

public static IEnumerable<T> getFlagValues<T>(this Enum enum, T enumInstance) where T : struct;

I am having trouble getting the casting to work, as I'm not allowed to constrain by Enum so I need to use struct.


Solution

  • I think that you mean like this:

    public static IEnumerable<T> getFlagValues<T>(this T enumValue) where T : struct {
      foreach (object o in Enum.GetValues(typeof(T))) {
        if (((int)o & (int)(object)enumValue) != 0) yield return (T)o;
      }
    }
    

    You only need one parameter, as you would call it on the enum value. Example:

    [Flags]
    public enum X { a = 1, b = 2, c = 4 }
    
    X x = X.a | X.c;
    
    foreach (var n in x.getFlagValues()) {
      Console.WriteLine(n);
    }
    

    Output:

    a
    c