Welcome to MSDN Blogs Sign in | Join | Help

Enumerating the Enums

While writing the code today I needed to enumerate all the values of an enum. I am sure many of you know about this, but I did not and hence here it is.

Suppose you have enum defined as follows and you want to enumerate all the possible values of Fruit.

      enum Fruit
    {
        Cherry,
        Apple,
        Orange,
        Banana
    }

Use the Enum.GetValues(Type T) method to achieve this. Here is the complete program:

using System;

public class EnumerateEnum
{
    enum Fruit
    {
        Cherry,
        Apple,
        Orange,
        Banana
    }

    public static void Main(string[] args)
    {
        foreach(Fruit f in Enum.GetValues(typeof(Fruit)))
        {
            Console.WriteLine(f);
        }
    }
}
Published Friday, April 15, 2005 6:54 PM by vipulm

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Enumerating the Enums

Wednesday, August 29, 2007 11:20 PM by Nic

Thanks, one slight error

Enum.GetValues returns a string[] so it should be foreach(string f in Enum.GetValues)

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker