Iterate through Enum values

  • Thread starter Thread starter Mark
  • Start date Start date
M

Mark

Assume you've declared an enum ....

public enum MyEnum { First, Second, Third }

Without knowing the values of the enum, is it possible to iterate through
all the possible values programmatically?

Thanks in advance.

Mark
 
Mark said:
Assume you've declared an enum ....

public enum MyEnum { First, Second, Third }

Without knowing the values of the enum, is it possible to iterate through
all the possible values programmatically?

Use the static System.Enum.GetNames method.

enum Color:
Red
Green
Blue

for item in System.Enum.GetNames(typeof(Color)):
print item
 
Mark,
You can use Enum.GetValues to get the list of values that belong to an Enum.
You can use Enum.GetNames to get the list of names of the values that belong
to an Enum.

Something like (untested):

foreach(MyEnum value in Enum.GetValues(typeof(MyEnum)))
{
// do something interesting with the value...
}

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top