Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get enum value by string or int

Tags:

c#

enums

How can I get the enum value if I have the enum string or enum int value. eg: If i have an enum as follows:

public enum TestEnum {     Value1 = 1,     Value2 = 2,     Value3 = 3 } 

and in some string variable I have the value "value1" as follows:

string str = "Value1"  

or in some int variable I have the value 2 like

int a = 2; 

how can I get the instance of enum ? I want a generic method where I can provide the enum and my input string or int value to get the enum instance.

like image 563
Abhishek Gahlout Avatar asked May 09 '14 11:05

Abhishek Gahlout


People also ask

Is enum string or int?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Can enum value be string?

Java provides a valueOf(String) method for all enum types. Thus, we can always get an enum value based on the declared name: assertSame(Element.LI, Element.

Can we compare enum with int?

Cast Int To Enum may be of some help. Go with the 2nd option. The 1st one can cause an exception if the integer is out of the defined range in your Enumeration. In current example I compare to 'magic number' but in real application I am getting data from integer field from DB.


1 Answers

No, you don't want a generic method. This is much easier:

MyEnum myEnum = (MyEnum)myInt;  MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString); 

I think it will also be faster.

like image 113
Kendall Frey Avatar answered Sep 20 '22 23:09

Kendall Frey