SyntaxHighlighter

Friday, 24 June 2011

How To Enumerate / Iterate an Enum

I often find myself needing to iterate/enumerate an enum. It's dead easy, but seem to always forget! What a fool ;)

Anyway, here ya go...

Public Enum MyEnum
    Jim = 0
    Bob = 1
End Enum

For Each e As MyEnum in [Enum].GetValues(GetType(MyEnum))
    Console.Write(String.Concat(e.ToString(), "=", Int32.Parse(e)))
Next

The GetValues method is quite useful as you can also get stuff like the length from it:
[Enum].GetValues(GetType(MyEnum)).Length.

The C# is pretty much the same just that [Enum] has no square brackets around it.

No comments:

Post a Comment