Question

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);
Was it helpful?

Solution

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();

OTHER TIPS

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.

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.

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top