Get Enum Values In Code Order

Created: December 21, 2014 Tagged As: C#, Language Share:

Using Enum.GetValues returns an array of an Enum's values that are sorted in value order. Consider the following Enum:

public enum MyEnum
{
   First = 1,
   Third = 3,
   Second = 2 
}

Using Enum.GetValues will return an array of First, Second, Third.

But what happens when you actually want to list them in the order in which they are declared in the code?

Use Type.GetFields - like this:

Type enumtype = typeof(MyEnum);
System.Reflection.FieldInfo[] fields = enumType.GetFields(); 
foreach (System.Reflection.FieldInfo f in fields)
{
   if (f.Name.Equals("value__"))
      continue;
   Console.WriteLine(f.Name + " - val: " + f.GetRawConstantValue());
} 

 

Problem solved!