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); } }
To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
Description. The java.lang.Enum.name() method returns the name of this enum constant, exactly as declared in its enum declaration.
By default enums have their own string values, we can also assign some custom values to enums.
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);
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)) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With