C# Enum.Parse() Bug

I actually didn’t think this was possible. Check out this line of C# code:

PersonType pt = (PersonType)Enum.Parse(typeof(PersonType), value.ToString(), true);

You can actually pass in an integer value that is not defined in the enum (in this case, the PersonType enum) and it will not throw an error — just assign the integer value to the pt variable.

C# Enum bug

In the image above you can see the the value variable holds the SqlInt32 value {6}, and the pt variable holds the integer value 6 after the Enum.Parse() call. That value isn’t defined in the enum definition.

Strange! I would have guessed that the cast would throw a runtime exception.

UPDATE: I’m not the first with this problem. However, there are warnings against using Enum.IsDefined(). What’s a poor coder to do? More here and here and here and here.

Here’s a snippet from the relevant Microsoft .NET Framework Developer’s Guide:

Do not use System.Enum.IsDefined(System.Type,System.Object) for enumeration range checks as it is based on the runtime type of the enumeration, which can change from version to version.
A later version of a library can add values to a shipping enumeration. Using IsDefined for data validation can be dangerous because existing code (which did not handle the new value) will treat the new value as valid input because IsDefined returns true for the new value. Check that the input is in the range of values your program can support and throw an exception if it is not.

Type safety be damned! Let’s all just use untyped variables!

Advertisements

1 Response to “C# Enum.Parse() Bug”


  1. 1 klos February 13, 2008 at 3:10 am

    Haha, hi,
    i’ve just discoverd the same problem.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: