Thursday, April 20, 2023

How to enumerate an enum in C# ?

In C#, you can enumerate an enum using the Enum.GetValues method. Here's an example:
  1. enum DaysOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
  2.  
  3. foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
  4. {
  5. Console.WriteLine(day);
  6. }
In this example, the DaysOfWeek enum is defined with seven possible values representing the days of the week. The Enum.GetValues method is called with the typeof(DaysOfWeek) argument to get an array of all the possible values of the enum. The foreach loop then iterates over the array and prints each value to the console. You can also use the Enum.GetName method to get the name of each enum value:
  1. foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
  2. {
  3. string name = Enum.GetName(typeof(DaysOfWeek), day);
  4. Console.WriteLine($"{day} = {name}");
  5. }
This code outputs the following:
  1. Monday
  2. Tuesday
  3. Wednesday
  4. Thursday
  5. Friday
  6. Saturday
  7. Sunday
  1. Monday = Monday
  2. Tuesday = Tuesday
  3. Wednesday = Wednesday
  4. Thursday = Thursday
  5. Friday = Friday
  6. Saturday = Saturday
  7. Sunday = Sunday

No comments:

Post a Comment