Monday 13 August 2018

c# - How to get the numeric value from a flags 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?


Answer



There is not much options as just make an if



List 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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...