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.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.