Search code examples
c#enumstype-systems

Why is enum casting allowed even when there is no valid value defined in the enumeration


When reading Jon Skeet's answer to this particular question How can I make it so my class variables can only be set to one of three choices? y learned something new I was not aware of in C# and I guess the CLR type system.

What is the reasoning behind this being legal:

public enum Tests
{
    Zero = 0,
    One,
    Two
}

var nonExistantTestsValue = (Tests)1000;

This will compile perfectly fine but I fail to see the reason of why it should be so. The whole point of enumerations as far as I can see is to limit to a certain number of options the value of a given variable of the specified type.

If the limitation imposed by the enum definition is so easily broken, what is the point (besides the readability issue)? You can obviously make sure it is a valid value using reflection but why isn't this done at compile time?

There is probably a good reason for this to work the way it does but I fail to see it.


Solution

  • It is allowed any value because you may mark the enum with the "Flags" attribute. That means you may compose any value by OR-ing various members of the enum itself. Basically the compiler is not smart enough to take care of any possible way where the enum is used.

    EDIT: found a previous post by Eric Lippert:

    Why does casting int to invalid enum value NOT throw exception?