A.I on the 1s and 0s

Alnur Ismail is a developer for Microsoft

C# - Iterating through an Enum

Today I came across a situation where iterating through an Enum would save me about 10 lines of code and some time. The quickest way is as follows:

foreach (MyEnum value in Enum.GetValues(typeof(MyEnum)))
{
  //...
}


 

 

Posted: Oct 06 2008, 05:27 PM by alnurismail | with 5 comment(s)
Filed under: ,

Comments

anytao said:

Smart idea;-)

# October 6, 2008 10:26 PM

Krzysztof Koźmic said:

Notice what happens when your enum has [FlagsAttribute] on it. This may not be the behavior you want.

# October 7, 2008 4:03 AM

Muhammad Shahid said:

nice and quikest way to iterate enumeration

# October 7, 2008 5:03 AM

Drakiula said:

I am doing this to avoid any casts:

public static IEnumerable<TEnum> EnumAsEnumerable<TEnum>()

{

   var enumType = typeof(TEnum);

   if (enumType == typeof(Enum))

       throw new ArgumentException("typeof(TEnum) == System.Enum", "TEnum");

   if (!(enumType.IsEnum))

       throw new ArgumentException(String.Format("typeof({0}).IsEnum == false", enumType), "TEnum");

   return Enum.GetValues(enumType).OfType<TEnum>();

}

# October 7, 2008 7:34 AM

alnurismail said:

Krzysztof - good catch. I should have been more specific and noted that this approach has only been tested with mutually exclusive elements.

Thanks,

Alnur

# October 7, 2008 9:49 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)