How to calculate the total number of items defined in an enum in C#?


An enum is a special "class" that represents a group of constants (unchangeable/readonly variables).

To create an enum, use the enum keyword (instead of class or interface), and separate the enum items with a comma −

By default, the first item of an enum has the value 0. The second has the value 1, and so on.

To get the integer value from an item, you must explicitly convert the item to an int

You can also assign your own enum values, and the next items will update the number accordingly −

Enums are often used in switch statements to check for corresponding values −

Example

class Program{
   enum Level{
      Low,
      Medium,
      High
   }
   public static void Main(){
      var myCount = Enum.GetNames(typeof(Level)).Length;
      System.Console.WriteLine(myCount);
      Console.ReadLine();
   }
}

Output

3

Example

class Program{
   enum Level{
      Low,
      Medium,
      High
   }
   public static void Main(){
      var myCount = Enum.GetNames(typeof(Level)).Length;
      for (int i = 0; i < myCount; i++){
         System.Console.WriteLine(i);
      }
      Console.ReadLine();
   }
}

Output

0
1
2

Updated on: 25-Sep-2020

936 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements