for (int i = (int)MY_ENUM.First; i <= (int)MY_ENUM.Last; i++)
{
//do work
}
Is there a more elegant way to do this?
for (int i = (int)MY_ENUM.First; i <= (int)MY_ENUM.Last; i++)
{
//do work
}
Is there a more elegant way to do this?
Take a look at Enum.GetValues:
foreach (var value in Enum.GetValues(typeof(MY_ENUM))) { ... }
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.
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.