Reputation: 9027
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
Upvotes: 10
Views: 21914
Reputation: 639
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);
Upvotes: 0
Reputation: 390
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.
Upvotes: 5
Reputation: 6017
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
Upvotes: 4
Reputation: 292555
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;
Upvotes: 17