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?
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.
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.
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.
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 };
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
.
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