Tuesday, August 11, 2020

How to get the Count of items defined in an Enum in C#

We 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 gives the number of items defined in the enum.

class Program
{
    static void Main(string[] args)
    {
        var testEnumCount = Enum.GetNames(typeof(TestEnum)).Length;
        Console.WriteLine(testEnumCount);
    }
}
enum TestEnum
{
    A = 1,
    B = 2,
    C = 3,
    D = 4,
    E = 5
}
The result count will be 5

No comments:

Post a Comment