Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a enum value from string in C#?

Tags:

c#

enums

I have an enum:

public enum baseKey : uint {       HKEY_CLASSES_ROOT = 0x80000000,     HKEY_CURRENT_USER = 0x80000001,     HKEY_LOCAL_MACHINE = 0x80000002,     HKEY_USERS = 0x80000003,     HKEY_CURRENT_CONFIG = 0x80000005 } 

How can I, given the string HKEY_LOCAL_MACHINE, get a value 0x80000002 based on the enum?

like image 294
Luiz Costa Avatar asked Oct 16 '09 15:10

Luiz Costa


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 is enum value in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

What is enum variable?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Is enum case sensitive C#?

If value is the string representation of the name of an enumeration value, the comparison of value with enumeration names is case-sensitive.


1 Answers

baseKey choice; if (Enum.TryParse("HKEY_LOCAL_MACHINE", out choice)) {      uint value = (uint)choice;       // `value` is what you're looking for  } else { /* error: the string was not an enum member */ } 

Before .NET 4.5, you had to do the following, which is more error-prone and throws an exception when an invalid string is passed:

(uint)Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE") 
like image 72
mmx Avatar answered Nov 15 '22 16:11

mmx