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

 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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements