-2

In C# it's possible to get the number of elements in an enum using this code:

int numberOfElements = Enum.GetNames(typeof(MyEnum)).Length;

How can this code be put into it's own function, be it a normal function, a static one, extension or a generic, so that the call to it can be simplified to something like:

int numberOfElements = GetEnumEntries(MyEnum);     // something like this
int numberOfElements = GetEnumEntries<MyEnum>();   // or this

For instance if I try this:

static public int GetEnumEntries(System.Type t) {
    int numberOfElements = System.Enum.GetNames(typeof(t)).Length;
}

I get the error 'the type or namespace t could not be found'

Matt Parkins
  • 24,208
  • 8
  • 50
  • 59
  • 3
    Just to correct your trial code: You should remove typeof(t), t is already a type, directly use t there. In the caller code than you would need to check as GetNumEntries( typeof( MyEnum )) - assuming you completed the method with a return). – Cetin Basoz Sep 19 '16 at 10:50

3 Answers3

3

You can use the generic approach. The hardest part is to limit the type parameter to an enum which can't be solely done at compile time. But with the method mentioned in this answer you can use this:

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;
}
2
private static int GetEnumEntries<T>()
{
    return Enum.GetNames(typeof(T)).Length;
}
Orkhan Alikhanov
  • 9,122
  • 3
  • 39
  • 60
0

typeof(t) will allways evaluate to System.Type instead of the type of actual type of your enumeration. Thus use t directly

System.Enum.GetNames(t).Length
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111