Is it possible to get the total number of items defined by an enum at runtime?
While it's pretty much the same question as this one, that question relates to C#, and as far as I can tell, the method provided there won't work in Objective-C.
You can use Enum. GetNames to return an IEnumerable of values in your enum and then. Count the resulting IEnumerable.
The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
The Enum. values() returns an array of all the enum constants. You can use the length variable of this array to get the number of enum constants. length is not a method of an array, it is a property field, so you'd use it without parentheses.
In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet . The order of the new list will be in the iterator order of the EnumSet . The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum.
An enum
is a plain-old-C type, therefore it provides no dynamic runtime information.
One alternative is to use the last element of an enum to indicate the count:
typedef enum { Red, Green, Blue, numColors } Color;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With