Enum.IsDefined for combined values not declared in the enum body


tags: ,
no comments

When you try to determine if an Enum value is defined in an Enum, it returns true only if the flags you’ve combined are explicitly declared in the Enum.

Consider this Enum:

[Flags]// Enum defined with a FlagsAttribute attribute.
enum Hue : sbyte
  Black = 0, //no color
  Red = 1,
  Green = 2,
  Blue = 4,
  Cyan = Green | Blue,//6
  Magenta = Red | Blue,//5
  BadColor = 127

The following line will return false:

var white = Hue.Red | Hue.Blue | Hue.Green//7

Even tho theoretically the enum combination is valid.

So to make sure a value doesn’t exceed the enums limit, but is not necessarily declared, we can use the following function:

(You can cashe the Enum.GetValues to improve performance)

public static bool IsDefined(this Enum value)
  dynamic dyn = value;
  var max = Enum.GetValues(value.GetType()).Cast<dynamic>().
    Aggregate((e1e2) => e1 | e2);
  return (max & dyn) == dyn;

The above function will solve the problem:

    static void Main(string[] args)
      var white = Hue.Red | Hue.Blue | Hue.Green//7
      var isDef1 = Enum.IsDefined(typeof(Enum), white); //false
      var isDef2 = white.IsDefined(); //true

Note: Performance not tested at all.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>