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?
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?
If your enum with colors is named MyColorEnumName
, Try
Enum.GetName(typeof(MyColorEnumName), enumColorValue)
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).
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.