How to get a numeric value from a flag enumeration?

Possible duplicate:
Enumerations returning an int value
How to get a numeric value from Enum?

THIS IS NOT A DUPLICATE THESE THESE THANKS FOR READING QUESTIONS MODES

Suppose I have several selected checkbox enumeration items:

[Flags] public enum Options { None = 0, Option_A = 1, Option_B = 2, Option_C = 4, Option_D = 8, } Options selected = Options.Option_A | Options.Option_B; 

The selected value must match 3 (i.e. 2 + 1)

How can I get this in int?

I saw examples where selected distinguishes ToString () and then split () in each option, for example.

 "Option_A | Option_B" --> { "Option_A", "Option_B" }, 

then recreated into the corresponding Enum and values ​​taken from it, but it is a little dirty. Is there a more direct way to get the sum of these values?

+4
source share
1 answer

There are not many options for how to simply do if

 List<int> composedValues = new .... if((selected & Option_A) == Options.Option_A) composedValues.Add((int)Options.Option_A); else if((selected & Option_B) == Options.Option_B) composedValues.Add((int)Options.Option_B); else if(...) 

Finally, you will get a list of all compositional values ​​of the result in the composedValues list.

If this is not what you are asking for, please specify.

+1
source

All Articles