Casting an out-of-range number to an enum in C# does not produce an exception

12,170

Solution 1

In C#, unlike Java, enums are not checked. You can have any value of the underlying type. This is why it's pretty important to check your input.

if(!Enum.IsDefined(typeof(MyEnum), value))
     throw new ArgumentOutOfRangeException();

Solution 2

Since your enum is based on int, it can accept any value that int can. And since you are telling the compiler explicitly (by casting) that it is ok to cast 4 into your enum it does so.

Solution 3

Each enum has an underlying numeric type (e.g. int) that is used for representation. Even if a value doesn't have a name, it's a possible value the enum can have.

Solution 4

What others didn't say: With casting, you tell the compiler that you know what you're doing. So if you tell it, treat this as an enum value, it does. The other posters pointed out why this is still allowed, as the C# compiler doesn't allow many bad things, even if you say you know what you're doing.

It would be really bad if the value was not allowed, because then you couldn't save a flag value as an int. Or, someone had to check whether the int is one of the allowed combinations, which can be a lot if you use a flag enum (with values that can be or'ed together).

Share:
12,170
Ted Smith
Author by

Ted Smith

Updated on June 04, 2022

Comments

  • Ted Smith
    Ted Smith almost 2 years

    The following code does not produce an exception but instead passes the value 4 to tst. Can anyone explain the reason behind this?

     public enum testing
     { 
        a = 1,
        b = 2,
        c = 3
     }
    
    testing tst = (testing)(4);