Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Use of Enumeration types


The class EnumTest from Microsoft's documentation pages of class System.Enum is reproduced here:

using System;

public class EnumTest {
    enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
    enum BoilingPoints { Celcius = 100, Fahrenheit = 212 };
    [FlagsAttribute]
    enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

    public static void Main() {

        Type weekdays = typeof(Days);
        Type boiling = typeof(BoilingPoints);

        Console.WriteLine("The days of the week, and their corresponding values in the Days Enum are:");

        foreach ( string s in Enum.GetNames(weekdays) )
            Console.WriteLine( "{0,-11}= {1}", s, Enum.Format( weekdays, Enum.Parse(weekdays, s), "d"));

        Console.WriteLine();
        Console.WriteLine("Enums can also be created which have values that represent some meaningful amount.");
        Console.WriteLine("The BoilingPoints Enum defines the following items, and corresponding values:");

        foreach ( string s in Enum.GetNames(boiling) )
            Console.WriteLine( "{0,-11}= {1}", s, Enum.Format(boiling, Enum.Parse(boiling, s), "d"));

        Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow;
        Console.WriteLine();
        Console.WriteLine("myColors holds a combination of colors. Namely: {0}", myColors);
    }
}

The output of the program is:

The days of the week, and their corresponding values in the Days Enum are:
Saturday   = 0
Sunday     = 1
Monday     = 2
Tuesday    = 3
Wednesday  = 4
Thursday   = 5
Friday     = 6

Enums can also be created which have values that represent some meaningful amount.
The BoilingPoints Enum defines the following items, and corresponding values:
Celcius    = 100
Fahrenheit = 212

myColors holds a combination of colors. Namely: Red, Blue, Yellow

Let me explain some details.

The first foreach loop traverses an array of strings returned by Enum.GetNames(weekdays). This is the array of strings "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday". The method Enum.Parse establishes a enumeration constant from the name of it (a string).

The method Enum.Format produces a formatted string of the second parameter (a value in the enumeration type). The following foreach statement produces equivalent results:

        foreach ( string s in Enum.GetNames(weekdays) )
            Console.WriteLine( "{0,-11}= {1}", s, (int)(Enum.Parse(weekdays, s)));

The second foreach loop is similar.

The last three lines show combined enumerations. It is noteworthy that the value of mycolor is formatted as Red, Blue, Yellow when printed. See also the Focus Box about combined enumerations.