Enum.GetName () for bit fields?

It seems that Enum.GetName() does not work if enum was decorated with the [Flags] attribute.

Documentation does not indicate anything related to this restriction.

I noticed that the debugger is able to display something like Tree | Fruit . Is there a way to get a text string describing the combined flags?


Displays the following Red code.

 public enum FavoriteColor { Red, Blue, WeirdBrownish, YouDoNotEvenWantToKnow, } var color = FavoriteColor.Red; Console.WriteLine(Enum.GetName(typeof(FavoriteColor), color)); // => "Red" 

While this one doesn’t output anything ....

 [Flags] public enum ACherryIsA { Tree = 1, Fruit = 2, SorryWhatWasTheQuestionAgain = 4, } var twoOfThree = ACherryIsA.Fruit | ACherryIsA.Tree; Console.WriteLine(Enum.GetName(typeof(ACherryIsA), twoOfThree)); // => "" 
+4
source share
2 answers
 string s = twoOfThree.ToString(); 

or

 Console.WriteLine(twoOfThree); 

If you want to do this manually, divide the value into bits and check which flags you need to add to create this flag. A bit of coding, but not much.

+7
source

Why not twoOfThree.ToString() ?

twoOfThree is 3, and ACherryIsA does not have an associated enumeration member for this value ...

+4
source

All Articles