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

Is there a more elegant way to do this?

3
  • 5
    Your code will only work for enums that are backed by ints, where the range is consecutive. Commented Sep 30, 2011 at 15:20
  • possible duplicate of C# Iterating through an enum? (Indexing a System.Array) Commented Jul 29, 2015 at 8:45
  • This question is similar to: How to enumerate an enum?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 13, 2024 at 23:14

4 Answers 4

62

You should be able to utilize the following:

foreach (MY_ENUM enumValue in Enum.GetValues(typeof(MY_ENUM)))
{
   // Do work.
}
Sign up to request clarification or add additional context in comments.

Comments

8

Take a look at Enum.GetValues:

foreach (var value in Enum.GetValues(typeof(MY_ENUM))) { ... }

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.