Looping through an enum in C# can be done using the Enum.GetValues method, which returns an array of the values of the constants in a specified enumeration. This allows you to use a
foreach loop to iterate over the enum values.
Here is a complete example with the enum definition and the loop:
using System;
public class Program
{
public enum DaysOfWeek
{
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
public static void Main()
{
foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
{
Console.WriteLine(day);
}
}
}
Additional Considerations
Enum Names: If you need to get the names of the enum values as strings, you can use the
Enum.GetNames method:
foreach (string name in Enum.GetNames(typeof(DaysOfWeek)))
{
Console.WriteLine(name);
}
Enum Parsing: You can parse a string to get the corresponding enum value using
Enum.Parse
Looping through an enum is a straightforward task in C# and can be done efficiently with the built-in
Enum.GetValues and Enum.GetNames methods. This approach ensures that your code is both clean and easy to maintain.
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.
Looping through an enum in C# can be done using the
Enum.GetValuesmethod, which returns an array of the values of the constants in a specified enumeration. This allows you to use aforeachloop to iterate over the enum values.Here’s how you can loop through an enum:
Example Enum Definition
Looping Through the Enum
You can loop through the
DaysOfWeekenum as follows:This will output:
Complete Example
Here is a complete example with the enum definition and the loop:
Additional Considerations
Enum Names: If you need to get the names of the enum values as strings, you can use the
Enum.GetNamesmethod:Enum Parsing: You can parse a string to get the corresponding enum value using
Enum.ParseChecking if Value is Defined: You can check if a value is defined in the enum using
Enum.IsDefinedLooping through an enum is a straightforward task in C# and can be done efficiently with the built-in
Enum.GetValuesandEnum.GetNamesmethods. This approach ensures that your code is both clean and easy to maintain.