We have an enum with members having random values, say
enum MyEnum
{
enumMember1 = 100,
enumMember2 = 10,
enumMember3 = 50
}
We couldnt iterate through the enum members in the order they have been defined! Enum.GetValues
and Enum.GetNames
both internally sort the members and gives the result!
iterating the array returned by Enum.GetNames or Enum.GetValues and doing a .ToString()
on each of the array elements gives us,
enumMember2, enumMember3, enumMember100.
Was just wondering if there is any out of the box approach to get the enum members in the order they have been created? Did search, didnt get much info! Thanks!
P.S. I would hate to get this done through a custom attribute! And While drafting it, i had a doubt if the IL for enum gets generated after sorting the Enum members, going to check it ryt away!
You can use reflection:
var values = typeof(MyEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
.Select (x => Enum.Parse(typeof(MyEnum), x.Name));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With