Wednesday, March 24, 2010

Using Enumerations

In order to use one of the enumerators, we must qualify it with the enumeration name. For example, the elements of the WeekDays enumeration are WeekDays.Sun, WeekDays.Mon, and so forth.
However, to convert an enum element to an integral type we must use a cast. For example:
int monday = (int) WeekDays.Mon;
long monday = (long) WeekDays.Mon;
In the following example, we declare three enumerations for WeekDays, Seasons, and Grades, This example demonstrates the various enumeration rules explained in the preceding sections.
//Example 7-4
//enum example
using System;
enum WeekDays {Sum, Mon, Tue, Wed, Thu, Fri, Sat };
enum Seasons { Summer = 1, Fall, Winter, Spring };
enum Grades { Pass = 65, Good = 75, VeryGood = 85, Distinct = 100 };
class MyClass
{
    static void Main()
    {
        int Sunday = (int) WeekDays.Sun;
        short summer = (short) Seasons.Summer;
        byte vGood = (byte) Grades.VeryGood;
        Console.WriteLine(“Sunday = {0}”, sunday);
        Console.WriteLine(“Summer = {0}”, summer);
        Console.WriteLine(“Very Good = {0}”, vGood);
    }
}

No comments:

Post a Comment