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);
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.
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.
An enum is considered an integer type. So you can assign an integer to a variable with an enum type.
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 .
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With