How to loop through all enum values in C#

In this article, let's learn how to loop through all enum values in C#.

To get started, first create a C# Console application in Visual Studio or VS Code.
Let's declare two enum types. For my example, here are two enums, Colors and Fruits. The Colors enum has five elements, and the Fruits enum has four elements.
enum Colors { Red, Orange, Green, Blue, Black};  
enum Fruits { Apple = 1, Banana = 2, Orange = 3, Peer = 4 };

To get all values of an enum, we can use the Enum.GetValues static method. The Enum.The GetValues method returns an array of all enum values. The following code snippet loops through all values of an enum and prints them on the Console.

foreach (int i in Enum.GetValues(typeof(Colors)))  
  Console.WriteLine($" {i}" );  

The Enum.The GetName method returns the constant's name in the specified enum with the specified value. The GetName method takes two arguments, the type of the enum and the index.

Console.Write($"{Enum.GetName(typeof(Colors), i)}");

The Enum.GetNames static method returns an array of the names of the constants in a specified enum. The following code snippet loops through an enum and prints all of its member names.

foreach (string name in Enum.GetNames(typeof(Fruits)))  

Let's take another example where we use a .NET enum, ConsoleColor. The following code snippet loops through, get ConsoleColor enum values, and sets the value as the Console's foreground color.

foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor)))  
  Console.ForegroundColor = color;  
  Console.WriteLine($"Foreground color set to {color}");  

The complete C# enum code example is listed in the following Listing 1.

using System;  
public class GetEnumValuesSample {  
    enum Colors {  
    enum Fruits {  
        Apple = 1, Banana = 2, Orange = 3, Peer = 4  
    public static void Main() {  
        Console.WriteLine("The values of the Colors Enum are:");  
        foreach(int i in Enum.GetValues(typeof(Colors))) {  
            Console.Write($ "{Enum.GetName(typeof(Colors), i)}");  
            Console.WriteLine($ " {i}");  
        // Get names of    
        foreach(string name in Enum.GetNames(typeof(Fruits))) {  
        //Let's go through all Console colors and set them as foreground    
        foreach(ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) {  
            Console.ForegroundColor = color;  
            Console.WriteLine($ "Foreground color set to {color}");  

Learn more here: Top 7 C# Enum Code Examples.

Similar Articles
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.