Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

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

$
0
0

 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)))

{

   Console.WriteLine(day);

} 


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)

{

    Console.WriteLine(day);

}


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


Viewing all articles
Browse latest Browse all 265

Latest Images

Trending Articles



Latest Images