using System;
public enum Colors
{
Red,
Green,
Blue
}
public class EnumerateEnum
{
public static void Main(string[] args)
{
// Enumerate the enum using a foreach loop.
foreach (Colors color in Colors)
{
Console.WriteLine("The color is {0}.", color);
}
}
}
This code first creates an enum called Colors. The Colors enum has three values:
Red, Green, and Blue.
The code then uses a foreach loop to enumerate the Colors enum. The foreach loop will iterate through each value of the
Colors enum and print the value to the console.
Using the Enum.GetValues() method:
C#
using System;
public enum Colors
{
Red,
Green,
Blue
}
public class EnumerateEnum
{
public static void Main(string[] args)
{
// Enumerate the enum using the Enum.GetValues() method.
object[] colors = Enum.GetValues(typeof(Colors));
// Iterate through the colors array and print each value to the console.
for (int i = 0; i < colors.Length; i++)
{
Colors color = (Colors)colors[i];
Console.WriteLine("The color is {0}.", color);
}
}
}
This code first creates an enum called Colors. The Colors enum has three values:
Red, Green, and Blue.
The code then uses the Enum.GetValues() method to get an array of all the values of the
Colors enum. The Enum.GetValues() method takes the type of the enum as a parameter.
The code then iterates through the array of values and prints each value to the console.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
There are two ways to enumerate an enum in C#:
C#
This code first creates an enum called
Colors. TheColorsenum has three values:Red,Green, andBlue.The code then uses a foreach loop to enumerate the
Colorsenum. The foreach loop will iterate through each value of theColorsenum and print the value to the console.Enum.GetValues()method:C#
This code first creates an enum called
Colors. TheColorsenum has three values:Red,Green, andBlue.The code then uses the
Enum.GetValues()method to get an array of all the values of theColorsenum. TheEnum.GetValues()method takes the type of the enum as a parameter.The code then iterates through the array of values and prints each value to the console.