tags:

views:

75

answers:

4

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?

+5  A: 
return ((MyEnumClass)n).ToString();
mquander
While I like Tomas's answer, this has the benefit of being to the point.Thanks.
WedTM
+1  A: 

If your enum with colors is named MyColorEnumName, Try

Enum.GetName(typeof(MyColorEnumName),  enumColorValue)
Charles Bretana
+3  A: 

Another option is to use the GetName static method:

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

This has the benefit that the code spaks 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).

Tomas Petricek
A: 

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 it's name in the ToString() override.

Marco
Why does so much apparently simple stuff in C# have painful performance implications?
Loren Pechtel
Because it's a programming language?
sfjedi
It's not like this is a common operation -- enum names can't even contain spaces, so you'll rarely want to use them as "friendly names" for something.
mquander