How to loop through all enum values in C#?

 

In C#, you can loop through all enum values using the Enum.GetValues method. Here's an example:

Suppose you have the following enum defined:

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

You can loop through all the enum values like this:

csharp
using System; class Program { static void Main() { // Loop through all enum values foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek))) { Console.WriteLine(day); } } }

In this example:

  1. We include the System namespace to use the Enum class.

  2. Inside the Main method, we use a foreach loop to iterate through all the enum values. The Enum.GetValues(typeof(DaysOfWeek)) method call returns an array of all the enum values.

  3. We print each enum value to the console.

When you run this C# program, it will output all the days of the week in the DaysOfWeek enum. The Enum.GetValues method is a flexible way to work with enum values, allowing you to loop through them or perform other operations programmatically.

Comments