September 8, 2010

Loop through Enumerations in C#

UPDATE: As commenter Tr3v has pointed out, there's a simpler way to achieve this with Enum.GetValues which avoids the parsing. Code snippet was updated.

I recently found out it's pretty easy to iterate through enums by first getting the names of the enums and then parsing those back as enum.

Note that this Enum.GetNames method uses reflection internally to read the enum metadata in memory.



Not the biggest discovery of the year here. I'll tag it as self-archiving :)

kick it on DotNetKicks.com
Shout it

2 comments:

  1. There is actually an easier and better way to do it:

    foreach (ImageSide imageSide in Enum.GetValues(typeof(ImageSide)))
    {
    Console.WriteLine(imageSide);
    }

    Using Enum.GetValues returns an array of the enum values themselves so although you still need to cast the value to an 'ImageSide' the foreach takes care of that for you.

    ReplyDelete
  2. Way simpler indeed. It doesn't avoid the cast but it avoids the parsing.

    I'll update my post. Thanks for pointing that out Tr3v!

    ReplyDelete