Home > Backend Development > C#.Net Tutorial > 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
Release: 2023-08-31 22:13:02
forward
805 people have browsed it

如何计算 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();
   }
}
Copy after login

Output

3
Copy after login

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();
   }
}
Copy after login

Output

0
1
2
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template