3

Is there a way to use an integer index to return the appropriate value from an enum? For example, if there is the enum Color {Red, Green, Blue) is there a function that for the value 0 will return Red, 1 will return Green, and 2 will return Blue?

kernanb
  • 566
  • 2
  • 6
  • 19
  • possible duplicate of [How to get C# Enum description from value?](http://stackoverflow.com/questions/2650080/how-to-get-c-enum-description-from-value) – Jason Aug 02 '11 at 01:05

4 Answers4

6

The Enum.GetName method: http://msdn.microsoft.com/en-us/library/system.enum.getname.aspx

Using your example,

Console.WriteLine(Enum.GetName(typeof(Color), 1));

prints "Green"

Chris Shain
  • 50,833
  • 6
  • 93
  • 125
  • 2
    Note that if you obfuscate your code, you will get jibberish instead of a human readable name. In that case, write your own translation method. – Brian Dishaw Aug 02 '11 at 01:05
3

You can cast your integer value to an enum.

Color c = (Color)0; //Color.Red
ahawker
  • 3,306
  • 24
  • 23
2
string color = ((Color)1).ToString(); //color is "Green"

Use the Enum.ToString() method.

http://msdn.microsoft.com/en-us/library/16c1xs4z.aspx

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
0

It's klunky but...

String Day = Enum.GetName(typeof(DayOfWeek), 3);
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69