8
public enum Animal
{
    Dog = 1,
    Cat = 2,
    Cow = 3
}

int animalID = 4;
if ((Animal)animalID == Animal.Dog) // does not throw exception

animalID can't be casted to Animal.
Why don't I get InvalidCastException when casting enum to integer fails?

Ray Booysen
  • 28,894
  • 13
  • 84
  • 111
Yeonho
  • 3,629
  • 4
  • 39
  • 61
  • Daniel what happens if you actually assign the cast to another object and check the value of the object after the assignment? you are just comparing with == wich does return a value but in fact is not really assigning anything... – Davide Piras Feb 17 '11 at 09:07
  • 1
    possible duplicate of [Casting ints to enums in C#](http://stackoverflow.com/questions/1758321/casting-ints-to-enums-in-c) – Ray Booysen Feb 17 '11 at 09:09
  • 1
    See this as well: http://stackoverflow.com/questions/618305/enum-casting – PHeiberg Feb 17 '11 at 09:10

2 Answers2

11

Because it's not an invalid cast.

The value you are casting is out of range for the enum (in this case) but it's not invalid.

As the approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong a cast from integer to enum is perfectly legal.

Source - MSDN

ChrisF
  • 134,786
  • 31
  • 255
  • 325
1

This is an intended behaviour and can be pretty useful. Consider enums defined with the [Flag] attribute.

btw, this is a dupe of Casting an out-of-range number to an enum in C# does not produce an exception

more answers may be in there :)

Community
  • 1
  • 1
MetaFight
  • 1,295
  • 14
  • 30