Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 617
InBetween Avatar asked Dec 17 '22 12:12

InBetween


1 Answers

Enumerations are essentially unique types that allow you to assign symbolic names to integral values. They are not used for restricting the allowable values of a variable...

like image 134
Akram Shahda Avatar answered May 16 '23 09:05

Akram Shahda