Search code examples
c#enumsenum-flags

How to tell the difference between a Flags enum and ordinary enum?


Is there any way to test reflectively if an enum is a [Flags] enum or if it's a regular enum?

I need the application to behave slightly differently if the enum is a Flags enum than if it's not a Flags enum.


Solution

  • You can test for attribute existence via reflection:

    System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);
    var isFlags = attrs.Any(attr => attr is FlagsAttribute);
    

    Or:

    var isFlags = typeof(MyEnum).GetCustomAttributes<FlagsAttribute>().Any();
    

    See: http://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx

    [OP Edit:]

    this worked, but the syntax is slightly wrong. This is correct:

    var isFlags = myEnum.GetType()
        .GetCustomAttributes(typeof(FlagsAttribute), false).Any();