If I had the value : "dog" and the enumeration:
public enum Animals
{
dog = 0 ,
cat = 1 ,
rat = 2
}
how could I get 0 for the value "dog" from Animals ?
EDIT:
I am wondering if there is index like acces. More commonn : how can I get the integer for string value.
Following is the method in C# to get the enum value by int. /// /// Method to get enumeration value from int value. /// /// /// public T GetEnumValue<T> (int intValue) where T : struct, IConvertible { if (!typeof (T).IsEnum) { throw new Exception ("T must be an Enumeration type.");
In Java (from 1.5), enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods and constructors to it. The main objective of enum is to define our own data types (Enumerated Data Types).
Last Updated : 21 Dec, 2018. Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. enum State {Working = 1, Failed = 0}; The keyword ‘enum’ is used to declare new enumeration types in C and C++.
Just cast the enum, e.g. int something = (int) Question.Role; The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int. However, as cecilphillip points out, enums can have different underlying types.
Just cast your enum value to integer:
Animals animal = Animals.dog;
int value = (int)animal; // 0
EDIT: if it turns out that you have name of enum value, then parse enum value and cast it to integer:
int value = (int)Enum.Parse(typeof(Animals), "dog");
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