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
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 are using .Net 4 you can use Enum.TryParse
PetType result;
if (Enum.TryParse<PetType>(pet, out result))
return (int)result;
else
throw something with an error message
Others already suggested to use Enum.Parse() but be careful with this method, because it doesn't just parse name of the enum, but also tries to match its value. To make it clear let's check small example:
PetType petTypeA = (PetType)Enum.Parse(typeof(PetType), "Dog");
PetType petTypeB = (PetType)Enum.Parse(typeof(PetType), "1");
The result of both parse calls will be PetType.Dog (which can be casted to int of course).
In most cases such behavior will be OK, but not always, and this is worth to remember how the Enum.Parse() method behaves.
you can use a string as parameter like
int pet=1;
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet.ToString());
Or
string pet="Dog";
PetType petType = (PetType)Enum.Parse(typeof(PetType), pet);
(PetType)Enum.Parse(typeof(PetType), pet)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.