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?
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.
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.)
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 .
return ((MyEnumClass)n).ToString();
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With