Enumerating the Enums

While writing the code today I needed to enumerate all the values of an enum. I am sure many of you know about this, but I did not and hence here it is.

Suppose you have enum defined as follows and you want to enumerate all the possible values of Fruit.

       enum Fruit
    {
        Cherry,
        Apple,
        Orange,
        Banana
    }

Use the Enum.GetValues(Type T) method to achieve this. Here is the complete program:

 using System;

public class EnumerateEnum
{
    enum Fruit
    {
        Cherry,
        Apple,
        Orange,
        Banana
    }

    public static void Main(string[] args)
    {
        foreach(Fruit f in Enum.GetValues(typeof(Fruit)))
        {
            Console.WriteLine(f);
        }
    }
}

Comments

  • Anonymous
    August 29, 2007
    Thanks, one slight error Enum.GetValues returns a string[] so it should be foreach(string f in Enum.GetValues)