Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get enum name when value is known

Tags:

c#

enums

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?

like image 530
WedTM Avatar asked Jul 25 '10 03:07

WedTM


People also ask

How do you find the value of an enum?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Is enum value or reference?

An enum type is a distinct value type (§8.3) that declares a set of named constants. declares an enum type named Color with members Red , Green , and Blue .


2 Answers

return ((MyEnumClass)n).ToString(); 
like image 139
mqp Avatar answered Oct 03 '22 18:10

mqp


Another option is to use the GetName static method:

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

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

like image 25
Tomas Petricek Avatar answered Oct 03 '22 19:10

Tomas Petricek