This has always bugged me. Perhaps someone with some hardcore knowledge of .NET internals can explain it to me.
Suppose I define an enum as follows:
public enum Foo
{
Eenie = 1,
Meenie = 2,
Miney = 3,
Moe = 4
}
Now, also suppose that somewhere in my code, I have the following code:
int bar = (Foo)5;
This will compile just fine, and no exception will be raised whatsoever, even though the value 5 is clearly not a valid value defined in Foo
.
Or, consider the following:
public void ProcessFoo(Foo theFoo)
{
// Do processing
}
public static void Main()
{
ProcessFoo((Foo)5);
}
Again, no exception.
In my mind, this should result in a type mismatch exception, because 5 is not a Foo
. But the designers chose not to do that.
Now, I've written an extension method that can verify that this is the case, and it's no big deal to invoke it to ensure that that's the case, but I have to use reflection to do it (with all its performance penalties and whatnot).
So again, what compelling reason is there that could possibly have driven the decision to not have a checked enum?
For reference, from the MSDN documentation for the Enum class:
When you define a method or property that takes an enumerated constant as a value, consider validating the value. The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration.