C# - Loop through all enum values

You can loop through all the values of an enum in C#. Enumerating through the values of an enum can be useful in scenarios where you need to perform an operation or access information for each enum value.

Here's an example of how to loop through all enum values in C#:



enum DaysOfWeek
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

class Program
{
    static void Main()
    {
        foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
        {
            Console.WriteLine(day);
        }
    }
}

Output of the above program is:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

In the above example, we have an enum 'DaysOfWeek' representing the days of the week. We use 'Enum.GetValues(typeof(DaysOfWeek))' to retrieve an array of all the enum values. Then, we use a 'foreach' loop to iterate through each value in the array. For each iteration, the current enum value is stored in the 'day' variable, and we can perform any desired operations within the loop.

The 'Enum.GetValues' method retrieves an array of the enum values in the order they are declared. By using a 'foreach' loop, you can process each enum value without explicitly specifying them individually.

In the loop, you can perform actions or access properties associated with each enum value as needed. In the example above, we simply print each enum value to the console.

By looping through all the enum values, you can easily iterate over each value and perform operations based on the enum's defined options.