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!
What about using a foreach loop, maybe you could work with that?
something like that perhaps?
Old question, but a slightly cleaner approach using LINQ's
.Cast<>()
Ancient question, but 3Dave's answer supplied the easiest approach. I needed a little helper method to generate a Sql script to decode an enum value in the database for debugging. It worked great:
I have it in a static method, so usage is:
Or, you can cast the System.Array that is returned:
But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?
Another solution, with interesting possibilities:
Array has a GetValue(Int32) method which you can use to retrieve the value at a specified index.
Array.GetValue