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.
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!


