Enumerations


An enumeration is a collection of named integer constants. The general form of an enumeration is shown below.

enum name { enumeration-list }

The name of the enumeration is specified by name. An enumeration defines a new type as specified by this name. The enumeration list is a comma-separated list of identifiers.

An example of an enumeration is shown below.

enum Fruit { Apple, Orange, Lemon, Pear }

Each of the symbols in the above enumeration stands for an integer value. By default, the first assigned value is zero and subsequent values are incremented by one. For example, consider the following program that includes the above enumeration.

// Enumeration1 - A First Enumeration

using System;

enum Fruit { Apple, Orange, Lemon, Pear }

class Program
{
    static void Main()
    {
        for (Fruit f = Fruit.Apple; f <= Fruit.Pear; f++)
            Console.WriteLine("{0} = {1}", f, (int)f);
    }
}

The output of this program is shown below.

Apple = 0
Orange = 1
Lemon = 2
Pear = 3

Despite enumerations being collections of named integers, no conversion exists between an enumerator and the integer data types. This means that when an enumerator is used where an integer is required an explicit type cast to integer should be used. In the above program, a variable f of the type Fruit was used in a for loop. By inference, it can be seen that Fruit is a separate data type, and it is actually a value type.

Initializing Enumerations

The previous example used the simplest possible schema for initialization of the enumerators. Other options are available. Values can be assigned to the enumerators in an enumeration. For example, consider the following change to the above program.

// Enumeration2 - Initializing Enumerators

using System;

enum Fruit { Apple, Orange, Lemon=100, Pear };

class Program
{
    static void Main()
    {
        Console.WriteLine("{0} = {1}", Fruit.Apple, (int)Fruit.Apple);
        Console.WriteLine("{0} = {1}", Fruit.Orange, (int)Fruit.Orange);
        Console.WriteLine("{0} = {1}", Fruit.Lemon, (int)Fruit.Lemon);
        Console.WriteLine("{0} = {1}", Fruit.Pear, (int)Fruit.Pear);
    }
}

The output of this program is shown below.

Apple = 0
Orange = 1
Lemon = 100
Pear = 101

Any particular enumerator can be assigned a value and all subsequent enumerators (that are not assigned values) are given values one greater than the previous value.

Specifying a Base Type for an Enumeration

By default, enumerations are based on the type int. Enumerations based upon other integer types can be created. As an example, the previous enumeration could be based upon the byte data type as follows.

enum Fruit : byte { Apple, Orange, Lemon, Pear };

In this case, Fruit.Apple is now a byte. Other integer types may be used in place of byte.