How to get the numeric value from a flags enum?

7.8k Views Asked by At

Possible Duplicate:
Enums returning int value
How to get the numeric value from the Enum?

THIS IS NOT A DUPLICATE OF EITHER OF THESE, THANKS FOR READING THE QUESTION MODS

Suppose I have a number of my flags enum items selected:

[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 value of selected should correspond to 3 (i.e. 2 + 1)

How can I get this into an int?

I've seen examples where the selected is cast ToString() and then split() into each option, e.g.

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

then reconstituted into the respective Enum, and the values taken from that, but it's a bit messy. Is there a more straight-forward way to get the sum of these values?

1

There are 1 best solutions below

7
On BEST ANSWER

There is not much options as just make an 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're asking for, please clarify.