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!
You can cast that Array to different types of Arrays:
or if you want the integer values:
You can iterate those casted arrays of course :)
How about a dictionary list?
and of course you can change the dictionary value type to whatever your enum values are.
You can simplify this using format strings. I use the following snippet in usage messages:
The D format specifier formats the enum value as a decimal. There's also an X specifier that gives hexadecimal output.
The G specifier formats an enum as a string. If the Flags attribute is applied to the enum then combined values are supported as well. There's an F specifier that acts as if Flags is always present.
See Enum.Format().
In the Enum.GetValues results, casting to int produces the numeric value. Using ToString() produces the friendly name. No other calls to Enum.GetName are needed.
Here is a simple way to iterate through your custom Enum object
You need to cast the array - the returned array is actually of the requested type, i.e.
myEnum[]
if you ask fortypeof(myEnum)
:Then
values[0]
etc