Computer >> Computer tutorials >  >> Programming >> C#

How to loop through all values of an enum in C#?


To loop through all the values of enum, use the Enum.GetValues().

Firstly, set an Enum −

public enum Grade { A, B, C, D, E, F };

Now, with foreach loop, you need to loop through Enum.GetValues(typeof(Grade)) −

foreach (Grade g in Enum.GetValues(typeof(Grade))) {
   Console.WriteLine(g);
}

Here is the complete code −

Example

using System;

public class EnumExample {
   public enum Grade { A, B, C, D, E, F };
   public static void Main() {
      foreach (Grade g in Enum.GetValues(typeof(Grade))) {
         Console.WriteLine(g);
      }
   }
}

Output

A
B
C
D
E
F