0

Possible Duplicate:
How do I enumerate an enum?

Suppose there is an enum

public enum Numbers {one, two, three };

What do I have to write instead of the three dots in the following code in order to get output "one", "two", "three":

foreach (Numbers n in ...) {
   Console.WriteLine (n.ToString ());
}

Of course, I would like to do it in a way such that modifying the enum definition does not require modification of the code within the foreach ( ).

Community
  • 1
  • 1
JohnB
  • 13,315
  • 4
  • 38
  • 65

4 Answers4

5

You could use:

foreach (Numbers n in Enum.GetValues(typeof(Numbers))) 
{
    Console.WriteLine(n.ToString());
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I must convert the Enum.GetValues result to (Numbers []) before the in, then it works. Not very pretty code, but definitely a solution to my problem. – JohnB Jul 21 '12 at 09:23
  • 2
    @JohnB do you need to? It worked out-of-the-box with C# 4.0 in my own programs – Alvin Wong Jul 21 '12 at 09:24
  • Sorry, no, of course you are right. If I write var n ..., then I must convert. – JohnB Jul 21 '12 at 09:26
  • 1
    @JohnB feel free to write your own static method wrapper to keep your code clean and handle the casting: `public static IEnumerable GetAll() { foreach(T value in Enum.GetValues(typeof(T))) yield return value; }` – Chris Sinclair Jul 21 '12 at 10:54
3

If you only need to get the names you can use this:

foreach (string name in Enum.GetNames(typeof(Numbers)))
{
    Console.WriteLine(name);
}

Of course if you want to actually use the Enum values, others have pointed out already.

Alvin Wong
  • 12,210
  • 5
  • 51
  • 77
0

use this: Enum.GetValues(type)

burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
0

Consider the following:

        foreach (var n in Enum.GetValues(typeof(Numbers)))
        {
            Console.WriteLine(n.ToString());
        }
Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113