How can I get the number of items defined in an enum?
You can use the static method Enum.GetNames which returns an array representing the names of all the items in the enum. The length property of this array equals the number of items defined in the enum
var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length;
You can use Enum.GetNames to return an IEnumerable of values in your enum and then .Count the resulting IEnumerable.
GetNames produces much the same result as GetValues but is faster.
A nifty trick I saw in a C answer to this question, just add a last element to the enum and use it to tell how many elements are in the enum:
enum MyType {
Type1,
Type2,
Type3,
NumberOfTypes
}
In the case where you're defining a start value other than 0, you can use NumberOfTypes - Type1 to ascertain the number of elements.
I'm unsure if this method would be faster than using Enum, and I'm also not sure if it would be considered the proper way to do this, since we have Enum to ascertain this information for us.
If you find yourself writing the above solution as often as I do then you could implement it as a generic:
public static int GetEnumEntries<T>() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an enumerated type");
return Enum.GetNames(typeof(T)).Length;
}