c# - Enum is defined does not work as expected -
this question has answer here:
- how check if flags of flag combination set? 16 answers
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
Post a Comment