c# - Enum.IsDefined with flagged enums -


i'm reading book c# 4.0 in nutshell, way think excellent book, advanced programmers use reference.

i looking on chapters basics, , came across trick tell if value defined in enum when using flagged enums.
book states using enum.isdefined doesn't work on flagged enums, , suggests work-around :

static bool isflagdefined(enum e) {     decimal d;     return (!decimal.tryparse(e.tostring(), out d); } 

this should return true if value defined in enum flagged.

can please explain me why works ?

thanks in advance :)

basically, calling tostring on enum value of type declared [flags] attribute return defined value:

somevalue, someothervalue 

on other hand, if value not defined within enum type, tostring produce string representation of value's integer value, e.g.:

5 

so means if can parse output of tostring number (not sure why author chose decimal), isn't defined within type.

here's illustration:

[flags] enum someenum {     somevalue = 1,     someothervalue = 2,     somefinalvalue = 4 }  public class program {     public static void main()     {         // defined.         someenum x = someenum.someothervalue | someenum.somefinalvalue;          console.writeline(x);          // not (no bitwise combination of 1, 2, , 4 produce 8).         x = (someenum)8;          console.writeline(x);     } } 

the output of above program is:

 someothervalue, somefinalvalue 8 

so can see how suggested method works.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -