Dumbo
Dumbo

Reputation: 14132

Get number of elements in an Enum type and iterate over them

Is there a way to iterate over elements in an enum type? Something like:

public enum MyEnum
{
   One,
   Two,
   Three,
}

foreach(var temp in MyEnum)
{
    //Do something
}

My be its possible by refelection or something?

Upvotes: 1

Views: 245

Answers (4)

KV Prajapati
KV Prajapati

Reputation: 94653

Use System.Array Enum.GetValues(Type) method.

 foreach(var temp in Enum.GetValues(typeof(MyEnum)))
  {
      //code
   }

Upvotes: 3

Habib
Habib

Reputation: 223412

var test = Enum.GetValues(typeof(MyEnum));
foreach (MyEnum e in test)
{
    Console.Write(e);
}

See Enum.GetValues

Upvotes: 0

sll
sll

Reputation: 62564

foreach (var name in Enum.GetNames(typeof(MyEnum))

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

Use Enum.GetValues(typeof(MyEnum)):

foreach(MyEnum temp in Enum.GetValues(typeof(MyEnum))) 
{ 
    //Do something 
}

Please note: I use MyEnum temp instead of var temp, because GetValues doesn't return a strong typed array.

Upvotes: 2

Related Questions