BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Using Foreach with an Enumeration

The Enum base class does not support the IEnumerable interface, preventing you from directly iterating through the values defined in an enumeration using foreach. However, this can be overcome by using the GetValues method described in this tip.

Enum Class

The Enum class is the base type for all enumerations. It contains a set of methods that can be used to process enumerated types. As the Enum class does not implement the IEnumerable interface it is not possible to directly loop through all of the declared values using the foreach statement. Fortunately, the Enum class provides a static method named GetValues. This returns all of the available enumerated values in order in an array. This array can then be iterated using foreach.

Using GetValues

The GetValues method is a static member of the Enum class. The method requires a single parameter holding the type of the enumeration to be processed. The following example demonstrates the method by looping through all of the constant values of an enumeration containing polygon types. In each case, the polygon name and number of sides (the integer value) is outputted. The example code can be pasted into the Program class of a console application.

enum Polygon
{
    Triangle = 3,
    Quadrilateral,
    Pentagon,
    Hexagon
}


static void Main(string[] args)
{
    foreach (Polygon p in Enum.GetValues(typeof(Polygon)))
    {
        Console.WriteLine("{0} ({1})", p, (int)p);
    }
}

/* OUTPUT

Triangle (3)
Quadrilateral (4)
Pentagon (5)
Hexagon (6)

*/
29 January 2008