Wednesday, April 16, 2008

Enum Class

An enum is a constant that contains words to represent numbers basically. For example, your program might refer to days of the week with numbers 1 to 7, but to make your code more readable you can create an enum to show that 1 is equal to "Sunday". Here is an example: Before:
private void DoWork(int today)
{
    if (today == 1  today == 2)
        TakeABreak();
    else
        GetToWork();
}
After:
public enum Day
{
    Sunday = 1,
    Monday = 2,
    Tuesday = 3,
    Wednesday = 4,
    Thursday = 5,
    Friday = 6,
    Saturday = 7
}

private void DoWork(Day today)
{
    if (today == Day.Sunday  today == Day.Saturday)
        TakeABreak();
    else
        GetToWork();
}
But say you have an outside program that refers to days of week by actual names and not numbers, you can still use your enum:
private void DoWork(string today)
{
    if (today == Day.Sunday.ToString() 
        today == Day.Saturday.ToString())
        TakeABreak();
    else
        GetToWork();
}
More Info: MSDN: Enum Class