This is completely plausible and the check is avoided first for performance reasons. Just imagine the CLR having to enumerate all the valid values and check whether yours falls in it, this no longer becomes a simple cast. The other reason is versioning. That is why you have Enum.IsDefined(…). Some developers now rely on this feature when dealing with an enum defining flags. When they want to set all flags they simply cast int.MaxValue to Enum
When defining an enum type, we can assign an int value to each of the enum members. Below is an example.
Now there are two behaviours that you may not be aware of. Firstly, given the above definition, you can actually assign any int value to a variable of type Status. Let say I have a class as below.
The following code will then happily compile and execute:
OK, who on earth would be doing something like that? Probably not many, but this leads on to the second behaviour: by default, the value of the enum will be 0, even if 0 is not one of the defined enum members.
So with the code below, the value of record.Status will be 0, which does not match any of the defined status values:
This behaviour could have an impact on your code if not handled properly. This is because when defining an enum…
View original post 95 more words