I have enum like this
public enum PetType
{
Dog = 1,
Cat = 2
}
I also have string pet = "Dog"
. How do I return 1? Pseudo code I'm thinking about is:
select Dog_Id from PetType where PetName = pet
The Java Enum has two methods that retrieve that value of an enum constant, name() and toString(). The toString() method calls the name() method, which returns the string representation of the enum constant.
Get 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.
Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
As you can see, it's pretty easy to decorate your enum values with string descriptions. This allows you to use a central location to set the value. I can even see a custom description attribute class that retrieves the description from a database. The use cases are there.
Use the Enum.Parse
method to get the enum value from the string, then cast to int:
string pet = "Dog";
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet);
int petValue = (int)petType;
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