In C#, you can enumerate an enum using the Enum.GetValues method. Here's an example:
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:
- enum DaysOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
- foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
- {
- Console.WriteLine(day);
- }
This code outputs the following:
- foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
- {
- string name = Enum.GetName(typeof(DaysOfWeek), day);
- Console.WriteLine($"{day} = {name}");
- }
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
- Sunday
- Monday = Monday
- Tuesday = Tuesday
- Wednesday = Wednesday
- Thursday = Thursday
- Friday = Friday
- Saturday = Saturday
- Sunday = Sunday
No comments:
Post a Comment