Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the number of enums as a constant?

From Total number of items defined in an enum, I see I can get the number of enums by using:

Enum.GetNames(typeof(Item.Type)).Length;

Works great!

But, I need this number as a constant number, so that I can use it in Unity's [Range(int, int)] feature.

private const int constEnumCount = Enum.GetNames(typeof(Item.Type)).Length;

The above does not work, because the enum count is not a constant number, so I cannot assign it to a constant variable.

How can I get the number of enums as a constant?

like image 295
Evorlor Avatar asked Apr 05 '16 17:04

Evorlor


People also ask

How do you find the enum constant?

You can use the name() method to get the name of any Enum constants. The string literal used to write enum constants is their name. Similarly, the values() method can be used to get an array of all Enum constants from an Enum type.

Can an enum be constant?

Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.

Which is used to find the index of enum constants?

Order is important in enums.By using the ordinal() method, each enum constant index can be found, just like an array index. valueOf() method returns the enum constant of the specified string value if exists.

How is enum constant defined?

The syntax for enumerated constants is to write the keyword enum, followed by the type name, an open brace, each of the legal values separated by a comma, and finally, a closing brace and a semicolon. Here's an example: enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };


1 Answers

It's not possible to get the number of enums as a const. Enum.GetNames uses reflection to get these things, and that's inherently a runtime operation. Therefore, it can't be known at compile time, which is a requirement for being const.

like image 186
Almo Avatar answered Sep 19 '22 13:09

Almo