1

Possible Duplicate:
C#: How to enumerate an enum?

Hi all I want to know that suppose I define a enum like

enum color
{
    red=4;
    blue=5;
    gray=6;
    green=8;
}

so can we print value of constant with the help of for loop, i means can we control it by loop; another question can we integrate it with dropdown list like as array. i means when we declare a element in side array suppose i write same color element, and those elment we can add with list or dropdown list(simple word binding with control)in asp.net , same thing can we perform with enum.

Stamos
  • 3,516
  • 1
  • 16
  • 40
Nishant Kumar
  • 5,629
  • 17
  • 63
  • 94

2 Answers2

6

Use Enum.GetValues():

Color[] colors = (Color[]) Enum.GetValues(typeof(Color));

I suspect that may have answered all your questions, but I didn't really follow the second half. If you still need help, please edit your question to be clearer.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • Surely if he's storing his colours as, for example, 4 for red (as opposed to the correct number representation of red) this method wouldn't work? – Blam Sep 06 '10 at 10:21
  • @Blam: I don't follow you, I'm afraid. – Jon Skeet Sep 06 '10 at 10:22
  • can you clearify your ansewer sir i means your comment on 2nd question ? – Nishant Kumar Sep 06 '10 at 10:24
  • foreach (int i in Enum.GetValue(typeof(color))){ console.writline(i);} it will print 4,5,6,8 what's problem in it..i am confused from your comment can you clearify your thoughts sir. – Nishant Kumar Sep 06 '10 at 10:28
  • @Nishant: You're implicitly casting to `int` there - if you change the variable to be of type `Color` instead, it'll be fine. – Jon Skeet Sep 06 '10 at 10:38
4

Use the static Enum.GetValues() method:

foreach (color value in Enum.GetValues(typeof(color)))
{
  //Do something here
}
softcr
  • 610
  • 3
  • 10