Home > .NET / CLR / C#, Code Snippets, Developer, Fixes & Tips > Quick Tip: Iterate through an enum in .NET

Quick Tip: Iterate through an enum in .NET

April 19th, 2009 Leave a comment Go to comments

Here’s a quicky for you. Iterating through an Enum in .NET, replace ‘IconResource‘ with the Enum you want to iterate.

C#

Array enumValues = System.Enum.GetValues(typeof(IconResource));

foreach (IconResource resource in enumValues)
{
	Console.WriteLine("Resource: {0}", resource);
}

VB.NET

Dim enumValues As Array = System.[Enum].GetValues(GetType(IconResource))

For Each resource As IconResource In enumValues
    Console.WriteLine("Resource: {0}", resource)
Next

Useful?

{lang: 'en-GB'}
Share
  1. April 20th, 2009 at 19:12 | #1

    Here is an other nice quicky for working with Enums. Hof often dit you have an int and wanted the Enum value for it? Her is a nice helper class so that you can do something like:
    myIntValue.ToEnum()

    public static class EnumHelper
    {
    public static T ToEnum(this int number)
    {
    return (T)Enum.ToObject(typeof(T), number);
    }
    }

  2. April 20th, 2009 at 19:15 | #2

    hmm… lost some text in the code above… It should be:
    tempCleaningStatus.ToEnum<CleaningStatus>()
    public static T ToEnum<T>(this int number)

  3. bsimpson644
    April 21st, 2009 at 00:12 | #3

    good, thanks for the info

  1. No trackbacks yet.