Total number of items defined in an enum
Enum.GetValues(typeof(MyEnum)).Length;
You can use the static method Enum.GetNames
which returns an array representing the names of all the items in the enum. The length property of this array equals the number of items defined in the enum
var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length;
The question is:
How can I get the number of items defined in an enum?
The number of "items" could really mean two completely different things. Consider the following example.
enum MyEnum
{
A = 1,
B = 2,
C = 1,
D = 3,
E = 2
}
What is the number of "items" defined in MyEnum
?
Is the number of items 5? (A
, B
, C
, D
, E
)
Or is it 3? (1
, 2
, 3
)
The number of names defined in MyEnum
(5) can be computed as follows.
var namesCount = Enum.GetNames(typeof(MyEnum)).Length;
The number of values defined in MyEnum
(3) can be computed as follows.
var valuesCount = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Distinct().Count();