Reputation: 1038
Say that I have variable whose value (for example, "listMovie"
) is the name of an enum
member:
public enum Movies
{
regMovie = 1,
listMovie = 2 // member whose value I want
}
In this example, I would like to get the value 2
. Is this 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);
}
}
Upvotes: 44
Views: 94200
Reputation: 40970
You want to get the Enum value from the string name. So you can use the Enum.Parse method.
int number = (int)Enum.Parse(typeof(TestAppAreana.MovieList.Movies), KeyVal)
You can also try Enum.TryParse to check whether parsing is successful or not.
Movies movie;
if (Enum.TryParse(KeyVal, true, out movie))
{
}
Upvotes: 17
Reputation:
Use:
var val= (int)Enum.Parse(typeof(TestAppAreana.MovieList.Movies), KeyVal)
Upvotes: 3
Reputation: 6366
Assuming that KeyVal
is a string representing the name of a certain enum you could do this in the following way:
int value = (int)Enum.Parse(typeof(TestAppAreana.MovieList.Movies), KeyVal);
Upvotes: 90