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
 
Back
Top