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

CsharpProgrammingServer Side Programming

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

 Live Demo

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
raja
Published on 31-Aug-2018 08:24:21
Advertisements