Iterating over all values in an enum is a common requirement in C#. You might need to populate a dropdown, validate input, or perform an action for each enum member. This guide covers every approach to enumerating through enums, including generic helpers and handling flags enums.
Defining a Sample Enum
All examples in this article use the following enum:
public enum Season
{
Spring,
Summer,
Autumn,
Winter
}
Method 1: Enum.GetValues with foreach
The most common approach uses Enum.GetValues, which returns an Array of all values defined in the enum:
foreach (Season season in Enum.GetValues(typeof(Season)))
{
Console.WriteLine(season);
}
Output:
Spring
Summer
Autumn
Winter
The cast from the returned Array to Season is implicit when you declare the loop variable with the enum type.
Method 2: Generic Enum.GetValues (.NET 5+)
Starting with .NET 5, a generic overload is available that returns a strongly-typed array, eliminating the need for typeof:
foreach (Season season in Enum.GetValues<Season>())
{
Console.WriteLine(season);
}
This is the cleanest approach for modern .NET applications.
Method 3: Enum.GetNames
If you only need the string names of the enum members, use Enum.GetNames:
foreach (string name in Enum.GetNames(typeof(Season)))
{
Console.WriteLine(name);
}
Or with the generic overload (.NET 5+):
foreach (string name in Enum.GetNames<Season>())
{
Console.WriteLine(name);
}
This returns the same strings you would get from calling .ToString() on each enum value, but without the overhead of boxing and unboxing.
Method 4: LINQ with Enum Values
You can use LINQ to filter, sort, or transform enum values:
var warmSeasons = Enum.GetValues<Season>()
.Where(s => s == Season.Spring || s == Season.Summer)
.ToList();
foreach (var season in warmSeasons)
{
Console.WriteLine(season);
}
Creating a Dictionary from an Enum
A common pattern is building a dictionary that maps integer values to names:
var seasonDict = Enum.GetValues<Season>()
.ToDictionary(s => (int)s, s => s.ToString());
// {0: "Spring", 1: "Summer", 2: "Autumn", 3: "Winter"}
Method 5: Casting to an Array for Index Access
If you need to access enum values by index:
Season[] seasons = (Season[])Enum.GetValues(typeof(Season));
Season third = seasons[2]; // Autumn
int count = seasons.Length; // 4
Or with the generic version:
Season[] seasons = Enum.GetValues<Season>();
Populating a Dropdown from an Enum
One of the most common real-world uses is populating a UI control:
// Windows Forms ComboBox
comboBox.DataSource = Enum.GetValues<Season>();
// ASP.NET MVC SelectList
var items = Enum.GetValues<Season>()
.Select(s => new SelectListItem
{
Value = ((int)s).ToString(),
Text = s.ToString()
})
.ToList();
Parsing Strings to Enum Values
To convert a string to an enum value, use Enum.Parse or Enum.TryParse:
// Throws ArgumentException if invalid
Season parsed = (Season)Enum.Parse(typeof(Season), "Summer");
// Safe parsing (returns false if invalid)
if (Enum.TryParse<Season>("Summer", out Season result))
{
Console.WriteLine(result); // Summer
}
// Case-insensitive parsing
Enum.TryParse<Season>("summer", ignoreCase: true, out Season result2);
Converting Between Enum and Integer
// Enum to int
int value = (int)Season.Autumn; // 2
// Int to enum
Season season = (Season)2; // Autumn
// Check if value is defined
bool isDefined = Enum.IsDefined(typeof(Season), 2); // true
bool isUndefined = Enum.IsDefined(typeof(Season), 99); // false
Working with Flags Enums
Flags enums use the [Flags] attribute and bitwise values, allowing combinations:
[Flags]
public enum FilePermissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
All = Read | Write | Execute
}
Iterating Individual Flags
Enum.GetValues returns all defined values, including combinations like All. To iterate only the individual flags that are set on a given value:
FilePermissions perms = FilePermissions.Read | FilePermissions.Write;
foreach (FilePermissions flag in Enum.GetValues<FilePermissions>())
{
if (flag != FilePermissions.None && perms.HasFlag(flag))
{
Console.WriteLine(flag);
}
}
// Output: Read, Write
Checking Individual Flags
FilePermissions perms = FilePermissions.Read | FilePermissions.Execute;
bool canRead = perms.HasFlag(FilePermissions.Read); // true
bool canWrite = perms.HasFlag(FilePermissions.Write); // false
bool canExecute = perms.HasFlag(FilePermissions.Execute); // true
Generic Helper Methods
You can create reusable helper methods for enum operations:
public static class EnumHelper
{
/// <summary>
/// Gets all values of an enum as a typed list.
/// </summary>
public static List<T> GetAllValues<T>() where T : struct, Enum
{
return Enum.GetValues<T>().ToList();
}
/// <summary>
/// Gets a dictionary mapping enum names to values.
/// </summary>
public static Dictionary<string, T> GetNameValuePairs<T>() where T : struct, Enum
{
return Enum.GetValues<T>()
.ToDictionary(e => e.ToString(), e => e);
}
/// <summary>
/// Safely parses a string to an enum, returning a default value if parsing fails.
/// </summary>
public static T ParseOrDefault<T>(string value, T defaultValue = default)
where T : struct, Enum
{
return Enum.TryParse<T>(value, ignoreCase: true, out T result)
? result
: defaultValue;
}
}
Usage:
List<Season> allSeasons = EnumHelper.GetAllValues<Season>();
Season parsed = EnumHelper.ParseOrDefault<Season>("summer", Season.Spring);
Quick Reference
| Task | Method |
|---|---|
| Iterate all values | Enum.GetValues<T>() |
| Iterate all names | Enum.GetNames<T>() |
| Parse string to enum | Enum.TryParse<T>(string, out T) |
| Enum to int | (int)enumValue |
| Int to enum | (T)intValue |
| Check if value is defined | Enum.IsDefined(typeof(T), value) |
| Check a flag is set | value.HasFlag(flag) |
Summary
The simplest way to enumerate through an enum in C# is foreach (var value in Enum.GetValues<T>()) on .NET 5 and later, or Enum.GetValues(typeof(T)) on older frameworks. Use Enum.GetNames when you only need the string names, and use the [Flags] attribute with HasFlag for bitwise enum combinations. For reusable code, create generic helper methods with the where T : struct, Enum constraint.