C# Iterating through an enum? (Indexing a System.Array)
Solution 1:
Array values = Enum.GetValues(typeof(myEnum));
foreach( MyEnum val in values )
{
Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}
Or, you can cast the System.Array that is returned:
string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));
for( int i = 0; i < names.Length; i++ )
{
print(names[i], values[i]);
}
But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?
Solution 2:
You need to cast the array - the returned array is actually of the requested type, i.e. myEnum[]
if you ask for typeof(myEnum)
:
myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum));
Then values[0]
etc
Solution 3:
You can cast that Array to different types of Arrays:
myEnum[] values = (myEnum[])Enum.GetValues(typeof(myEnum));
or if you want the integer values:
int[] values = (int[])Enum.GetValues(typeof(myEnum));
You can iterate those casted arrays of course :)
Solution 4:
How about a dictionary list?
Dictionary<string, int> list = new Dictionary<string, int>();
foreach( var item in Enum.GetNames(typeof(MyEnum)) )
{
list.Add(item, (int)Enum.Parse(typeof(MyEnum), item));
}
and of course you can change the dictionary value type to whatever your enum values are.