Loop Through Enum Values In C#

How to loop through all enum values in C#.

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

Here are two enums.
  1. enum Colors { Red, Orange, Green, Blue, Black};  
  2. enum Fruits { Apple = 1, Banana = 2, Orange = 3, Peer = 4 };  

Enum.GetValues method returns an array of all enum values. The following code snippet loops through and prints values of enum members.

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

Enum.GetName method returns the name of the constant in the specified enum that has the specified value.

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

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

  1. foreach (string name in Enum.GetNames(typeof(Fruits)))  
  2. {  
  3.   Console.WriteLine(name);  
  4. }  

The following code snippet loops through and gets ConsoleColor enum values and sets the value as the Console’s foreground color.

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

The complete code is listed in Listing 1.

  1. using System;  
  2. public class GetEnumValuesSample {  
  3.     enum Colors {  
  4.         Red,  
  5.         Orange,  
  6.         Green,  
  7.         Blue,  
  8.         Black  
  9.     };  
  10.     enum Fruits {  
  11.         Apple = 1, Banana = 2, Orange = 3, Peer = 4  
  12.     };  
  13.     public static void Main() {  
  14.         Console.WriteLine("The values of the Colors Enum are:");  
  15.         foreach(int i in Enum.GetValues(typeof(Colors))) {  
  16.             Console.Write($ "{Enum.GetName(typeof(Colors), i)}");  
  17.             Console.WriteLine($ " {i}");  
  18.         }  
  19.         Console.WriteLine();  
  20.         // Get names of    
  21.         foreach(string name in Enum.GetNames(typeof(Fruits))) {  
  22.             Console.WriteLine(name);  
  23.         }  
  24.         // Let's go through all Console colors and set them as foreground    
  25.         foreach(ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) {  
  26.             Console.ForegroundColor = color;  
  27.             Console.WriteLine($ "Foreground color set to {color}");  
  28.         }  
  29.         Console.ReadKey();  
  30.     }  
  31. }  
Learn more here: Top 7 C# Enum Code Examples