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?
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.
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.
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.
If value is the string representation of the name of an enumeration value, the comparison of value with enumeration names is case-sensitive.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With