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

Luiz Costa picture Luiz Costa · Oct 16, 2009 · Viewed 107k times · Source

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?

Answer

Mehrdad Afshari picture Mehrdad Afshari · Oct 16, 2009
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")