Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of enum member by its name?

Tags:

c#

.net

enums

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);     } } 
like image 281
Navajyoth CS Avatar asked Feb 04 '14 19:02

Navajyoth CS


People also ask

How do you find the value of an enum?

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.

What does enum name return?

Description. The java.lang.Enum.name() method returns the name of this enum constant, exactly as declared in its enum declaration.

Can enums have a value?

By default enums have their own string values, we can also assign some custom values to enums.


2 Answers

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); 
like image 163
Paweł Bejger Avatar answered Sep 16 '22 17:09

Paweł Bejger


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)) {  } 
like image 21
Sachin Avatar answered Sep 18 '22 17:09

Sachin