# Wednesday, March 07, 2007
« Dell Inspiron 1150 in the ER | Main | I added an AboutMe section »
How can you have an invalid enum?  Why would you want an invalid enum?  I know it seems almost contradictory to have an invalid enum, but I have run into the situation once or twice.  Usually its where there is a switch statement that does some particular action based off an enum and in that switch statement there is a default that throws an exception just in case another programmer would add a new enum value without updating the switch statement.  You may actually want to unit test and verify that an invalid enum would throw an exception.  Here's one way to achieve this, use an explicit cast:

enum DayOfWeek
{
    Monday,
    Tuesday
}

DayOfWeek badDayOfWeek = (DayOfWeek)(-1);

Trivial!  Yet its not something you may think of, because we've generally been trained to think that enums are ALWAYS supposed to be valid.

Better yet, get rid of your enums and your switch statements.

Comments are closed.