Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.GetName() for bit fields?

It looks like Enum.GetName() doesn't work if the enum has been decorated with a [Flags]attribute.

The documentation doesn't specify anything related to this limitation.

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


Following code display Red.

public enum FavoriteColor
{
    Red,
    Blue,
    WeirdBrownish,
    YouDoNotEvenWantToKnow,
}

var color = FavoriteColor.Red;
Console.WriteLine(Enum.GetName(typeof(FavoriteColor), color));   // => "Red"

Whereas 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));   // => ""
like image 813
nulltoken Avatar asked Jun 08 '12 12:06

nulltoken


1 Answers

string s = twoOfThree.ToString();

or:

Console.WriteLine(twoOfThree);

If you want to do it manually, split the value into bits, and test what flags you need to add to make that flag. A bit of coding, but not much.

like image 134
Marc Gravell Avatar answered Sep 28 '22 00:09

Marc Gravell