Enumerations

Enumerations

An enumeration is a list of enumerated values that are associated with a specific type. Enumerations are declared using the enum keyword, as shown here:

enum Color
{
    Red, Yellow, Green
}

An enumeration value is accessed using the dot operator.

Color background = Color.Red;

Unlike C++ enumerators, C# enumerators must be used with the enum type name. This reduces the likelihood of name clashes between enumerations and improves readability.

An enumeration assigns scalar values to each of the enumerators in the enumerated list. By default, the base type used to store enumerated values is int, which can be changed to any of the scalar types, as shown here:

enum Color : byte
{
    Red, Yellow, Green
}

The values of enumerators begin at 0 unless an initial value is specified—in this case, 1:

enum Color : byte
{
    Red = 1, Yellow, Green
}

Enumerators are assigned sequential values unless an initializer is specified for the enumerator. The value of an enumerator must be unique, but need not be sequential or ordered.

enum Color : byte
{
    Red = 1, Yellow = 42, Green = 27
}

Although an enumerator is based on the int type (or another scalar value), you can’t assign an enumerator to or from an int value without being explicit about your intentions, as shown here:

Color background = (Color)27;
int oldColor = (int)background;


Part III: Programming Windows Forms