FontysICT-sem1

Enum

Definition of Enum

Example

enum Day
{
   Sunday,
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday
}

The following code is then possible:

Day d;
d = Day.Wednesday;

Another example is the months of the year: January through….

Why should I use enums?

This becomes clear from the following example: A calendar application where you can call an item to a weekday. Initial:

void AddToCalendar(int day, string item)

The days in the week are created as constants. Sunday is 0, Monday is 1, etc. The same for the months in the year: January is 0, February is 1, etc.

Now if you make a programming error:

AddToCalendar(February, "whole month of spectacular offers");

Then here bravely adds the item on Monday… Oops.

With enums, the compiler stops you, then it becomes after all:

void AddToCalendar(Day day, string item)

since Month is not a Day.

additional