Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); 
like image 208
Ted Smith Avatar asked Mar 06 '09 10:03

Ted Smith


People also ask

What does Do not cast to an out of range enumeration value?

Enumerations in C++ come in two forms: scoped enumerations in which the underlying type is fixed and unscoped enumerations in which the underlying type may or may not be fixed.

Can you cast an enum in C?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.

Can we assign value to enum in C?

An enum is considered an integer type. So you can assign an integer to a variable with an enum type.

How do I assign an int to an enum?

Use the Type Casting to Convert an Int to Enum in C# The correct syntax to use type casting is as follows. Copy YourEnum variableName = (YourEnum)yourInt; The program below shows how we can use the type casting to cast an int to enum in C#. We have cast our integer value to enum constant One .


2 Answers

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(); 
like image 77
mmx Avatar answered Sep 25 '22 05:09

mmx


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.

like image 41
Alex Reitbort Avatar answered Sep 22 '22 05:09

Alex Reitbort