Get the value of an enum member by his name?

Let's say I have a variable whose value (for example "listMovie") is the name of the member enum:

public enum Movies
{
    regMovie = 1,
    listMovie = 2 // member whose value I want
}

In this example, I would like to get the value 2. Is it possible? Here is what I tried:

public static void getMoviedata(string KeyVal)
{
    if (Enum.IsDefined(typeof(TestAppAreana.MovieList.Movies), KeyVal))
    {
        //Can print the name but not value
        ((TestAppAreana.MovieList.Movies)2).ToString(); //list
        Enum.GetName(typeof(TestAppAreana.MovieList.Movies), 2);
    }
}
+6
source share
3 answers

Assuming it KeyValis a string representing the name of a specific enumeration, you can do it like this:

int value = (int)Enum.Parse(typeof(TestAppAreana.MovieList.Movies), KeyVal);
+27
source

You want to get the value of Enum from the string name. That way you can use the Enum.Parse method .

int number = (int)Enum.Parse(typeof(TestAppAreana.MovieList.Movies), KeyVal)

Enum.TryParse, , .

Movies movie;
if (Enum.TryParse(KeyVal, true, out movie))
{

}
+4

:

var val= (int)Enum.Parse(typeof(TestAppAreana.MovieList.Movies), KeyVal)
+1

Source: https://habr.com/ru/post/1525296/


All Articles