Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you loop through an enum in C#?

Tags:

c#

enums

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

Is there a more elegant way to do this?

like image 380
coder Avatar asked Sep 30 '11 15:09

coder


People also ask

Can we loop through enum in C?

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.

Can you loop through an enum?

An enum can be looped through using Enum. GetNames<TEnum>() , Enum. GetNames() , Enum. GetValues<TEnum>() , or Enum.

Can you loop through all enum values in C#?

Yes. Use GetValues() method in System. Enum class.

Can you loop through an enum C ++?

C++ Enumeration Iteration over an enumThere is no built-in to iterate over enumeration.


2 Answers

You should be able to utilize the following:

foreach (MY_ENUM enumValue in Enum.GetValues(typeof(MY_ENUM))) {    // Do work. } 
like image 80
Bernard Avatar answered Sep 29 '22 17:09

Bernard


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.

like image 34
Adam Lear Avatar answered Sep 29 '22 18:09

Adam Lear