Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I get InvalidCastException when casting enum to integer fails?

Tags:

c#

.net

enums

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?

like image 752
Yeonho Avatar asked Feb 17 '11 09:02

Yeonho


1 Answers

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

like image 83
ChrisF Avatar answered Oct 02 '22 20:10

ChrisF