[c#] Total number of items defined in an enum

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

This question is related to c# .net enums

The answer is


I've run a benchmark today and came up with interesting result. Among these three:

var count1 = typeof(TestEnum).GetFields().Length;
var count2 = Enum.GetNames(typeof(TestEnum)).Length;
var count3 = Enum.GetValues(typeof(TestEnum)).Length;

GetNames(enum) is by far the fastest!

|         Method |      Mean |    Error |   StdDev |
|--------------- |---------- |--------- |--------- |
| DeclaredFields |  94.12 ns | 0.878 ns | 0.778 ns |
|       GetNames |  47.15 ns | 0.554 ns | 0.491 ns |
|      GetValues | 671.30 ns | 5.667 ns | 4.732 ns |

If you find yourself writing the above solution as often as I do then you could implement it as a generic:

public static int GetEnumEntries<T>() where T : struct, IConvertible 
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("T must be an enumerated type");

    return Enum.GetNames(typeof(T)).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();

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


A nifty trick I saw in a C answer to this question, just add a last element to the enum and use it to tell how many elements are in the enum:

enum MyType {
  Type1,
  Type2,
  Type3,
  NumberOfTypes
}

In the case where you're defining a start value other than 0, you can use NumberOfTypes - Type1 to ascertain the number of elements.

I'm unsure if this method would be faster than using Enum, and I'm also not sure if it would be considered the proper way to do this, since we have Enum to ascertain this information for us.


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.


For Visual Basic:

[Enum].GetNames(typeof(MyEnum)).Length did not work with me, but [Enum].GetNames(GetType(Animal_Type)).length did.


I was looking into this just now, and wasn't happy with the readability of the current solution. If you're writing code informally or on a small project, you can just add another item to the end of your enum called "Length". This way, you only need to type:

var namesCount = (int)MyEnum.Length;

Of course if others are going to use your code - or I'm sure under many other circumstances that didn't apply to me in this case - this solution may be anywhere from ill advised to terrible.


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
        }
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to enums

Enums in Javascript with ES6 Check if value exists in enum in TypeScript Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'? TypeScript enum to object array How can I loop through enum values for display in radio buttons? How to get all values from python enum class? Get enum values as List of String in Java 8 enum to string in modern C++11 / C++14 / C++17 and future C++20 Implementing Singleton with an Enum (in Java) Swift: Convert enum value to String?