3
Answers

Enum elements count

Zagiel

Zagiel

15y
9.2k
1
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?
Answers (3)