In C#, you can loop through all enum values using the Enum.GetValues method. Here's an example:
Suppose you have the following enum defined:
csharp
enum DaysOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
You can loop through all the enum values like this:
csharp
using System;
class Program
{
static void Main()
{
// Loop through all enum values
foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
{
Console.WriteLine(day);
}
}
}
In this example:
We include the
Systemnamespace to use theEnumclass.Inside the
Mainmethod, we use aforeachloop to iterate through all the enum values. TheEnum.GetValues(typeof(DaysOfWeek))method call returns an array of all the enum values.We print each enum value to the console.
When you run this C# program, it will output all the days of the week in the DaysOfWeek enum. The Enum.GetValues method is a flexible way to work with enum values, allowing you to loop through them or perform other operations programmatically.
Comments
Post a Comment