Monday, February 09, 2009

.Net Enum.Parse()

Let’s say you have the following enumerated type:

enum Rainbow
{
    Red,
    Orange,
    Yellow,
    YELLOW,
    Green,
    Blue,
    Indigo = 8,
    Violet = 8
}

You can then use Enum.Parse() method to convert a string to the enumerated value. This is demonstrated by doing the following:

Rainbow rainbowValue = (Rainbow)Enum.Parse(typeof(Rainbow), myString, true);

Where myString is a string variable that holds the string you want to convert.

When you perform Enum.Parse() you should be aware of a few things that may not be obvious.

1) String numbers can be used. For example “1” will convert to Rainbow.Orange.

2) A string number that is out of range doesn’t throw an exception. You must use Enum.IsDefined() to make sure that the number is in range. For example if you assign “100” to mystring you won’t see an exception thrown.

3) The last argument of the Enum.Parse() method allows you to ignore the case. If you do ignore the case the first value found in the enum will be used. If you plan on ignoring case then you should make sure that the values of the enum are unique ignoring case. The compiler will fail if you have enum Rainbow { Red, Red}, but will not fail if you have enum Rainbow { Red, RED}.

4) You can assign the same number to two different enum values. Surprisingly this doesn’t throw a compiler warning or error. Equally surprisingly the last number is chosen. For example if you assign “8” or “Indigo” to mystring, the enum variable will be set to Rainbow.Violet.

5) A comma separated string can work, but it is probably not what you want unless you are using the FlagsAttribute with the enum type and assigning number values in a way that can be masked. For example if you assign “Orange, Green” to mystring, the enum variable will be set to Rainbow.Blue. This is because you are actually doing Rainbow.Orange | Rainbow.Green which is actual (1 | 4) and in binary (0x0001 | 0x0100) with is 5 (0x0101).

Conclusion

If you are using Enum.Parse() to convert strings to enum variables you should keep these things in mind. Dispending on what you are doing these issues may not be a problem, or they may be hidden gotchas with unintended results.