kernanb
kernanb

Reputation: 586

C# Enum Reverse Indexing

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

Answers (4)

Steve Wellens
Steve Wellens

Reputation: 20620

It's klunky but...

String Day = Enum.GetName(typeof(DayOfWeek), 3);

Upvotes: 0

ahawker
ahawker

Reputation: 3374

You can cast your integer value to an enum.

Color c = (Color)0; //Color.Red

Upvotes: 4

Evan Mulawski
Evan Mulawski

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

Chris Shain
Chris Shain

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

Related Questions