user1544165
user1544165

Reputation:

Get enum index from string

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];

Upvotes: 4

Views: 19240

Answers (2)

Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

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
}

Upvotes: 3

code4life
code4life

Reputation: 15794

Like this?

int animalNumber = (int)Enum.Parse(typeof(Animals), "Dog");

Upvotes: 17

Related Questions