Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total number of items defined in an enum

Tags:

c#

.net

enums

How can I get the number of items defined in an enum?

like image 909
SO User Avatar asked May 13 '09 05:05

SO User


People also ask

How do you find the number of elements in an enum?

Use the len() class to get the number of elements in an enum, e.g. len(Color) . The len() function returns the length (the number of items) of an object and can directly be passed an enum. Copied! The len() function returns the length (the number of items) of an object.

How do you measure enum size?

There are multiple ways to check the size of an enum type. Second, using object methods keys() , values() , entries() methods to get the array list of keys, values, and key-value multiple constants. These methods return the array of enum constants. using the length method on the array, prints the size.

How many values can an enum have?

In theory, an ENUM column can have a maximum of 65,535 distinct values; in practice, the real maximum depends on many factors.


2 Answers

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; 
like image 74
Kasper Holdum Avatar answered Oct 10 '22 04:10

Kasper Holdum


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(); 
like image 30
Timothy Shields Avatar answered Oct 10 '22 06:10

Timothy Shields