Reputation: 586
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?
Upvotes: 5
Views: 7254
Reputation: 20620
It's klunky but...
String Day = Enum.GetName(typeof(DayOfWeek), 3);
Upvotes: 0
Reputation: 3374
You can cast your integer value to an enum.
Color c = (Color)0; //Color.Red
Upvotes: 4
Reputation: 55334
string color = ((Color)1).ToString(); //color is "Green"
Use the Enum.ToString() method.
http://msdn.microsoft.com/en-us/library/16c1xs4z.aspx
Upvotes: 2
Reputation: 51339
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"
Upvotes: 6