Export (0) Print
Expand All

Enumerations

Visual Studio 2008

C# enables you to create your own set of named constants using the enum keyword. These data types allow you to declare a set of names or other literal values that define all the possible values that can be assigned to a variable.

For example, if your program deals with the days of the week, you might want to create a new type called DayOfWeek. You could then declare a new variable of DayOfWeek type, and assign it a value. Using this data type allows your code to be more readable, and also makes it less likely that an illegal or unexpected value will be assigned to the variable.

public enum DayOfWeek
{
    Sunday = 0,
    Monday = 1, 
    Tuesday = 2, 
    Wednesday = 3, 
    Thursday = 4, 
    Friday = 5, 
    Saturday = 6
}

class Program
{
    static void Main()
    {
        DayOfWeek day = DayOfWeek.Monday;
        int i = (int) DayOfWeek.Monday;

        System.Console.WriteLine(day);  // displays Monday
        System.Console.WriteLine(i);    // displays 1
    }
}

Here are several more features of enum data types that might be useful.

Displaying the Enumeration's Literal Values

If you need to access the name or words you are using in your enum data type, you can do so using the ToString() method, as follows:

DayOfWeek day = DayOfWeek.Wednesday;
System.Console.WriteLine(day.ToString());  // displays Wednesday

Setting the Default Values

By default, the first value in the enumerated type is a zero. You can specify a different initial value, as follows:

enum Color { Red = 1, Yellow = 2, Blue = 3 };

In fact, you can define unique integer values for all the values:

enum Medal { Gold = 30, Silver = 20, Bronze = 10 };

Community Additions

ADD
Show:
© 2014 Microsoft