for (int i = (int)MY_ENUM.First; i <= (int)MY_ENUM.Last; i++) { //do work }
Is there a more elegant way to do this?
you can iterate the elements like: for(int i=Bar; i<=Last; i++) { ... } Note that this exposes the really-just-an-int nature of a C enum. In particular, you can see that a C enum doesn't really provide type safety, as you can use an int in place of an enum value and vice versa.
An enum can be looped through using Enum. GetNames<TEnum>() , Enum. GetNames() , Enum. GetValues<TEnum>() , or Enum.
Yes. Use GetValues() method in System. Enum class.
C++ Enumeration Iteration over an enumThere is no built-in to iterate over enumeration.
You should be able to utilize the following:
foreach (MY_ENUM enumValue in Enum.GetValues(typeof(MY_ENUM))) { // Do work. }
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.
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