Skip to content

Enum elements count

Zagiel

Asked Mar 29, 2009, 6:19 AM EDT3 answers
Share
LinkedInX
Is there a way to get the amount of elements in an enum? AFAIK there was no such thing in C++ and I'm afraid neither is in C#, although I find it quite neccessary: Imagine you've got an enum and a static dictionary of enum elements mapped to f.e. strings. You fill this dictionary with values at run-time start, but you want to make sure that whenever you enlarge the enum, you won't forget to enlarge the dictionary too. So it'd be nice to have something like an assert(myDictionary.Count == myEnum.Count) performed at the end of dictionary init. The only way I manage to achieve such a self-check is to have an const int lastMyEnumElement = (int)MyEnumType.lastMyEnumElement and do an assert(myDictionary.Count == lastMyEnumElement + 1), but this is useless if you add a new enum element and forget to update lastMyEnumElement. Self-updating MyEnumType.Count would solve the problem. Is there any other way?

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    try:

    Enum.GetNames(typeof(myEnum)).Length;
    0
  • 2 short replies
    • 0
      Wonderful, thank you.
      0
    • 0
      No problem :)
      0