Cloud Training (Online)




C# Tips and Tricks #1 – Get the Total Number of Items in an Enum in C# ?

You can get the total number of items defined in an enum in C# using the combination of the Enum.GetNames method and the Length property.

How to get the Total Number of Items in an Enum in C# ?

The static method Enum.GetNames returns an array that represents the names of all the items that is present in the enum. You can apply the Length property which retrieves the number of items present.

using System;
namespace DeveloperPublishCsharpSample
{
    public enum Actors
    {
        Ajith,
        Vijay,
        Surya
    }
    class Program
    {
        static void Main(string[] args)
        {
            var totalMembersInEnum = Enum.GetNames(typeof(Actors)).Length;
            Console.WriteLine(totalMembersInEnum);
            Console.ReadLine();
        }
    
    }
  
}

Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.