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

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?

This question is related to c# enums

The answer is


With some error handling...

uint key = 0;
string s = "HKEY_LOCAL_MACHINE";
try
{
   key = (uint)Enum.Parse(typeof(baseKey), s);
}
catch(ArgumentException)
{
   //unknown string or s is null
}

var value = (uint)Enum.Parse(typeof(basekey), "HKEY_LOCAL_MACHINE", true);

This code snippet illustrates obtaining an enum value from a string. To convert from a string, you need to use the static Enum.Parse() method, which takes 3 parameters. The first is the type of enum you want to consider. The syntax is the keyword typeof() followed by the name of the enum class in brackets. The second parameter is the string to be converted, and the third parameter is a bool indicating whether you should ignore case while doing the conversion.

Finally, note that Enum.Parse() actually returns an object reference, that means you need to explicitly convert this to the required enum type(string,int etc).

Thank you.


var value = (uint) Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE");  

Alternate solution can be:

baseKey hKeyLocalMachine = baseKey.HKEY_LOCAL_MACHINE;
uint value = (uint)hKeyLocalMachine;

Or just:

uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;

Using Enum.TryParse you don't need the Exception handling:

baseKey e;

if ( Enum.TryParse(s, out e) )
{
 ...
}