I'm writing a method which determines the highest value in a .NET enumeration so I can create a BitArray with one bit for each enum value:
pressedKeys = new BitArray(highestValueInEnum<Keys>());
I need this on two different enumerations, so I turned it into a generic method:
/// <summary>Returns the highest value encountered in an enumeration</summary>
/// <typeparam name="EnumType">
/// Enumeration of which the highest value will be returned
/// </typeparam>
/// <returns>The highest value in the enumeration</returns>
private static int highestValueInEnum<EnumType>() {
int[] values = (int[])Enum.GetValues(typeof(EnumType));
int highestValue = values[0];
for(int index = 0; index < values.Length; ++index) {
if(values[index] > highestValue) {
highestValue = values[index];
}
}
return highestValue;
}
As you can see, I'm casting the return value of Enum.GetValues() to int[], not to EnumType[]. This is because I can't cast EnumType (which is a generic type parameter) to int later.
The code works. But is it valid? Can I always cast the return from Enum.GetValues() to int[]?