4

How can I get the index integer (in this case 0) from an enum when I have a string to compare against the enum?

Enum:

public enum Animals
{
    Dog = 0,
    Cat = 1
}

string myAnimal = "Dog";

Obviously the following line won't work but it might help you to understand what I want to achieve:

int animalNumber = (int)Animals.[myAnimal];
1

2 Answers 2

17

Like this?

int animalNumber = (int)Enum.Parse(typeof(Animals), "Dog");
Sign up to request clarification or add additional context in comments.

Comments

3
Types t;
if(Enum.TryParse(yourString, out t)) // yourString is "Dog", for example
{
    // use t           // In your case (int)t
}
else
{
    // yourString does not contain a valid Types value
}

OR

try
{
    Types t = (Types)Enum.Parse(typeof(Types), yourString);
    // use t           // In your case (int)t
}
catch(ArgumentException)
{
    // yourString does not contain a valid Types value
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.