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?
Getting Integer from Enum On the other hand, to get the integer value from an enum, one can do as follows, by using the getValue method. The getValue method simply returns the internal value of the enum that we store within the value variable.
The [Flag] attribute is used when Enum represents a collection of multiple possible values rather than a single value. All the possible combination of values will come. The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With