WedTM
WedTM

Reputation: 2647

Get enum name when value is known

I have an enum that has different colors in it. I would like to pass some function an int and have it return the color name that is in the enum in that position.

What's the way to do this?

Upvotes: 40

Views: 62033

Answers (7)

Sheriff
Sheriff

Reputation: 868

((YourEnum)Value).ToString()

For eg.

((MyEnum)2).ToString()

Note: Points to remember, your enum should be decorated by [Flag] and enum value must be greater than 0.

Upvotes: 0

Sheo Dayal Singh
Sheo Dayal Singh

Reputation: 1683

Below is the example to get Enum name based on the color value.

  class Program
     {
          //Declare Enum
          enum colors {white=0,black=1,skyblue=2,blue=3 }
      static void Main(string[] args)
        {
          // It will return single color name which is "skyblue"
             string colorName=Enum.GetName(typeof(colors),2);

          //it will returns all the color names in string array.
          //We can retrive either through loop or pass index in array.
             string[] colorsName = Enum.GetNames(typeof(colors));

         //Passing index in array and it would return skyblue color name
             string colName = colorsName[2];

             Console.WriteLine(colorName);
             Console.WriteLine(colName);
             Console.ReadLine();
        }
    }

Upvotes: 0

Marco
Marco

Reputation: 1346

If you care about performance beware of using any of the suggestions given here: they all use reflection to give a string value for the enum. If the string value is what you'll need most, you are better off using strings. If you still want type safety, define a class and a collection to define your "enums", and have the class echo its name in the ToString() override.

Upvotes: 2

jle
jle

Reputation: 9489

In c# 6 you can use nameof.

nameof(YourEnum.Something)

results in:

something

Upvotes: 14

Tomas Petricek
Tomas Petricek

Reputation: 243116

Another option is to use the GetName static method:

Enum.GetName(typeof(MyEnumClass), n);

This has the benefit that the code speaks for itself. It should be obvious that it returns the name of the enum (which may be a bit difficult to realize when you use for example the ToString method).

Upvotes: 58

Charles Bretana
Charles Bretana

Reputation: 146557

If your enum with colors is named MyColorEnumName, Try

Enum.GetName(typeof(MyColorEnumName),  enumColorValue)

Upvotes: 7

mqp
mqp

Reputation: 72015

return ((MyEnumClass)n).ToString();

Upvotes: 79

Related Questions