Search code examples
c#enumsiterationsystem.array

C# Iterating through an enum? (Indexing a System.Array)


I have the following code:

// Obtain the string names of all the elements within myEnum 
String[] names = Enum.GetNames( typeof( myEnum ) );

// Obtain the values of all the elements within myEnum 
Array values = Enum.GetValues( typeof( myEnum ) );

// Print the names and values to file
for ( int i = 0; i < names.Length; i++ )
{
    print( names[i], values[i] ); 
}

However, I cannot index values. Is there an easier way to do this?

Or have I missed something entirely!


Solution

  • 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 ?