tags:

views:

384

answers:

4

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

+5  A: 

Enum.GetNames(typeof(MyEnum)).Length;

Matt Hamilton
It's faster to use the GetNames method.
Qua
You're right - a quick test proved that. I will update the answer.
Matt Hamilton
+3  A: 

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

GetNames produces much the same result as GetValues but is faster.

Lucas Willett
+8  A: 

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

Qua
Agreed ... here's a link i found http://www.csharp411.com/c-count-items-in-an-enum/
Rashmi Pandit
+3  A: 

From the previous answers just adding code sample.

 class Program
    {
        static void Main(string[] args)
        {
            int enumlen = Enum.GetNames(typeof(myenum)).Length;
            Console.Write(enumlen);
            Console.Read();
        }
        public enum myenum
        {
            value1,
            value2
        }
    }
jvanderh