Saturday, October 21, 2006

It is legal to cast any integer value into an Enum even if the value is out of the range defined in your Enum

I've been researching Enums recently and have found some very interesting facts about them, for example:

It is legal to cast any integer value into an enum even if the value is not defined in the enum.

this is valid:

public enum TestEnum {
Enum1 = 1,
Enum2 = 2,
Enum3 = 3
}

...


TestEnum t = (TestEnum)10; //WTF?
Console.Write(t.ToString());
Console.Read();


Consider when the value comes from another source, such as a database


If you are dealing with Enums, you should read this article by Krzysztof Cwalina, it is a very complete reference / guideline for Enums; then when you get into Nullable Enums it gets even more interesting, I'll post a few things I'm doing with Enums

No comments: