c# - Enum is defined does not work as expected -


this question has answer here:

i have following enum need validate based on client selections

    [flags]     enum colour     {         black = 1,         blue = 2,         green = 4,         yellow = 8     }    var isvalid = enum.isdefined(typeof(colour), 5); 

why returning false if 5 valid value (colour.black | colour.green)

because proper result. "if enumtype enumeration defined using flagsattribute attribute, method returns false if multiple bit fields in value set value not correspond composite enumeration value, or if value string concatenation of names of multiple bit flags." see msdn details how isdefined works.

upd: solution enum:

static class enumextensions {     public static bool issuitable(type enumtype, int value)     {         if (!enumtype.isenum)         {             throw new argumentexception(nameof(enumtype));         }          var entities = enum.getvalues(enumtype);         int composite = 0;         foreach (var entity in entities)         {             composite |= (int)entity;         }          return (composite | value) == composite;     } } 

it gives result:

var suit = enumextensions.issuitable(typeof(colour), 5); // true var suit2 = enumextensions.issuitable(typeof(colour), 333); //false 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -