Casting numeric enumeration value does not throw exception

  • Thread starter Thread starter Steve Wilkinson
  • Start date Start date
S

Steve Wilkinson

This may or may not have been asked before so forgive me if it has.

Why is an exception not thrown when a numeric value is cast to an enumerated
type which does not contain that numeric value ?

e.g.

private enum TestEnum
{
None = 0,
Value1 = 5,
Value2 = 10,
Value3 = 15
}

The following doesn't throw an exception:

TestEnum te = (TestEnum)6;

Can anyone explain why and if it is classed as behaviour by design what is
the reasoning behind this ?

Thanks

Steve
 
Ultimately, enums *are* simply values of the underlying base-type (Int32
by default); and explicit casting simply changes between the two
(section 13.2.2 of ECMA334 quoted below).

Note that you can use Enum.IsDefined(...) to check a value's validity,
but you also need to consider [Flags] enums, the default value (zero)
that is explitely always valid etc.

Marc

13.2.2 Explicit enumeration conversions
The explicit enumeration conversions are:
• From sbyte, byte, short, ushort, int, uint, long, ulong, char, float,
double, or decimal to
any enum-type.
• From any enum-type to sbyte, byte, short, ushort, int, uint, long,
ulong, char, float,
double, or decimal.
• From any enum-type to any other enum-type.
An explicit enumeration conversion between two types is processed by
treating any participating enum-type
as the underlying type of that enum-type, and then performing an
implicit or explicit numeric conversion
between the resulting types. [Example: Given an enum-type E with and
underlying type of int, a conversion
from E to byte is processed as an explicit numeric conversion (§13.2.1)
from int to byte, and a
conversion from byte to E is processed as an implicit numeric conversion
(§13.1.2) from byte to int. end
example]
 
Thanks guys,

I've already added an explicit check, I was just curious of the reasoning.

Steve
 
Back
Top