How to get int value for enumeration in Enumeration

If I had the meaning: "dog" and the listing:

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

How could I get 0 for the value "dog" in animals?

EDIT:

I am wondering if there is an index like acces. More common: how can I get an integer for a string value.

+4
source share
4 answers

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

To convert from a string to an enumeration and then convert the resulting enumeration to 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);
}

, , , ( ), , Animal, Animals.

+4

enum :

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

EDIT: , enum, :

int value = (int)Enum.Parse(typeof(Animals), "dog"); 
+7
+5

: var r = (int)Animals.dog

+3

All Articles