What is the procedure for iterating over an enum in C#?

 To iterate through an enum in C#, you can use the `foreach` loop or the `Enum.GetValues` method.

Here's an example of using a `foreach` loop to iterate through an enum:

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

foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))




This will output all the values of the `DaysOfWeek` enum: `Monday`, `Tuesday`, `Wednesday`, `Thursday`, `Friday`, `Saturday`, and `Sunday`.

Alternatively, you can use the `Enum.GetValues` method to get an array of all the enum values and iterate through it using a `for` loop or a `foreach` loop:

DaysOfWeek[] values = (DaysOfWeek[])Enum.GetValues(typeof(DaysOfWeek));

foreach (DaysOfWeek day in values)




This will also output all the values of the `DaysOfWeek` enum in the same order.

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

how to use coalesce in PostgreSQL?

To use the `COALESCE` function in PostgreSQL, follow these steps: 1. Start by writing a SELECT statement or any other query where you want t...