Enums are a great way to define a set of named constants in C#, but what if you need to iterate over all values dynamically? You can use** Enum.GetValues()** to loop through an enum without hardcoding values.
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
foreach (Days day in Enum.GetValues(typeof(Days)))
{
Console.WriteLine(day);
}
This would output the following:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Alternative: Using Enum.GetNames()
If you only need the string names, use Enum.GetNames() instead:
foreach (string name in Enum.GetNames(typeof(Days)))
{
Console.WriteLine(name);
}
Walt is a computer scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
Last updated on: