Home  >  Article  >  Backend Development  >  How to count the total number of items defined in an enumeration in C#?

How to count the total number of items defined in an enumeration in C#?

WBOY
WBOYforward
2023-08-31 22:13:02761browse

如何计算 C# 中枚举中定义的项目总数?

An enumeration is a special "class" that represents a set of constants (unchangeable/read-only variable).

To create an enumeration, use the enum keyword (instead of a class or interface), and separate Keep the html code and do not add new content Enumeration items are separated by commas −

By default, the value of the first item in the enumeration is 0. The value of the second item is 1, and so on

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

You can also assign your own enum value and the next item will update the number Depending on the situation −

Enumerations are often used in switch statements to check the corresponding value −

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

The above is the detailed content of How to count the total number of items defined in an enumeration in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete