13

If I had the value : "dog" and the enumeration:

public enum Animals
{
  dog = 0 ,
  cat = 1 ,
  rat = 2
}

how could I get 0 for the value "dog" from Animals ?

EDIT:

I am wondering if there is index like acces. More commonn : how can I get the integer for string value.

0

4 Answers 4

7

Just cast your enum value to integer:

Animals animal = Animals.dog;
int value = (int)animal; // 0

EDIT: if it turns out that you have name of enum value, then parse enum value and cast it to integer:

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

4 Comments

He has a string not enum.
@TuTran can you that he edited question?
I think OP's question is clear: how could I get 0 for the value "dog"
@TuTran as you can see above, it's not clear
6

To answer your question "how can I get the integer for string value":

To convert from a string into an enum, and then convert the resulting enum to an int, you can do this:

public enum Animals
{
    dog = 0,
    cat = 1,
    rat = 2
}

...

Animals answer;

if (Enum.TryParse("CAT", true, out answer))
{
    int value = (int) answer;
    Console.WriteLine(value);
}

By the way, normal enum naming convention dictates that you should not pluralize your enum name unless it represents flag values (powers of two) where multiple bits can be set - so you should call it Animal, not Animals.

Comments

5

You can either cast it to Int, or iterate over all values using the Enum.GetValues Method which retrieves an array of the values of the constants in a specified enumeration.

Comments

3

What about: var r = (int)Animals.dog

5 Comments

Need to parse "dog" to Animals.dog first
@Tu Tran - really, are you sure? I don't agree... Try it yourself.
Absolutely sure. See the answer of Matthew Watson, I totally agree with him.
@Tu Tran - please copy and paste my code and try it yourself.
Because the question has been edited (as Sergey Berezovskiy noticed), I think you should check the question again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.