mo.notono.us

Thursday, June 23, 2005

Tip of the Day: Enum default values

If you have an enum declared like this:
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
and in your code you have a member variable defined like this:
Days _day;
you might not expect that _day would have a value at this point. Unfortunately you’d be wrong - _day would equal Days.Sat. The default value of an enum E is (E)0, which in this case is the first Days value, Sat.

You might think that you could get around this feature by initializing the first Days value to 1, like this:
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
Now, surely _day would have no value? Nope – enums are value types, integers to be exact, and their default value is always 0. So in this case _day would simply equal 0. Additionally, if someone attempted to set the value of _day to 8, you might think this would cause an error. Again you’d be wrong. The value of _day would simply be 8.

The lesson to be learned here is to never assume that an enum variable will have a value limited to one of the values specified by your enum. Additionally you may want to explicitly create a first enum option None, giving yourself a visual clue that the enum variable has not had a value set. And lastly, use a switch/case statement when you check the value of an enum, and always include a default: statement

For more on enums, see the help file: Value Types - enum

0 Comments:

Post a Comment

<< Home