32
for (int i = (int)MY_ENUM.First; i <= (int)MY_ENUM.Last; i++)
{
    //do work
}

Is there a more elegant way to do this?

coder
  • 1,274
  • 1
  • 13
  • 19
  • 5
    Your code will only work for enums that are backed by ints, where the range is consecutive. – Jeremy McGee Sep 30 '11 at 15:20
  • possible duplicate of [C# Iterating through an enum? (Indexing a System.Array)](http://stackoverflow.com/questions/482729/c-sharp-iterating-through-an-enum-indexing-a-system-array) – Ian Goldby Jul 29 '15 at 08:45

4 Answers4

60

You should be able to utilize the following:

foreach (MY_ENUM enumValue in Enum.GetValues(typeof(MY_ENUM)))
{
   // Do work.
}
Bernard
  • 7,908
  • 2
  • 36
  • 33
8

Enums are kind of like integers, but you can't rely on their values to always be sequential or ascending. You can assign integer values to enum values that would break your simple for loop:

public class Program
{
    enum MyEnum
    {
        First = 10,
        Middle,
        Last = 1
    }

    public static void Main(string[] args)
    {
        for (int i = (int)MyEnum.First; i <= (int)MyEnum.Last; i++)
        {
            Console.WriteLine(i); // will never happen
        }

        Console.ReadLine();
    }
}

As others have said, Enum.GetValues is the way to go instead.

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
7

Take a look at Enum.GetValues:

foreach (var value in Enum.GetValues(typeof(MY_ENUM))) { ... }
kevingessner
  • 18,559
  • 5
  • 43
  • 63
2

The public static Array GetValues(Type enumType) method returns an array with the values of the anEnum enumeration. Since arrays implements the IEnumerable interface, it is possible to enumerate them. For example :

 EnumName[] values = (EnumName[])Enum.GetValues(typeof(EnumName));
 foreach (EnumName n in values) 
     Console.WriteLine(n);

You can see more detailed explaination at MSDN.

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46
Michiel
  • 21
  • 1