Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting total number of enum items

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.

like image 680
Josh Buhler Avatar asked Sep 24 '09 01:09

Josh Buhler


People also ask

How do you count enums?

You can use Enum. GetNames to return an IEnumerable of values in your enum and then. Count the resulting IEnumerable.

How do I get a list of all enum values?

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.

How do you count enums in Java?

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.

Can you have a list of enums?

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.


1 Answers

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; 
like image 80
Darren Avatar answered Oct 04 '22 13:10

Darren