To enumerate all values of an enum in C#, you can use the Enum.GetValues
method. Here’s a step-by-step explanation with examples:
1. Using Enum.GetValues
(Non-Generic Method)
This method retrieves an array of the enum’s values. Each value must be cast to the enum type.
using System;
public enum Color
{
Red,
Green,
Blue
}
public class Program
{
public static void Main()
{
// Loop through all enum values
foreach (var value in Enum.GetValues(typeof(Color)))
{
Color color = (Color)value;
Console.WriteLine(color);
}
}
}
Output:
Red
Green
Blue
2. Using Enum.GetValues<T>
(Generic Method in .NET 5+)
In .NET 5+ or .NET Core, use the generic Enum.GetValues<T>
for type safety and cleaner code:
foreach (Color color in Enum.GetValues<Color>())
{
Console.WriteLine(color);
}
3. Get Enum Names with Enum.GetNames
If you need the names (strings) of the enum values instead of the values themselves:
foreach (string name in Enum.GetNames(typeof(Color)))
{
Console.WriteLine(name);
}
// Or with the generic method in .NET 5+:
foreach (string name in Enum.GetNames<Color>())
{
Console.WriteLine(name);
}
Output:
Red
Green
Blue
4. Get Both Names and Values
Loop through the enum values and format the output to include both the name and its underlying value:
foreach (Color color in Enum.GetValues(typeof(Color)))
{
Console.WriteLine($"{color} ({(int)color})");
}
Output:
Red (0)
Green (1)
Blue (2)
5. Handle Flags Enums
For enums marked with [Flags]
, Enum.GetValues
returns all explicitly defined values (including combined flags):
[Flags]
public enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
ReadWrite = Read | Write // Explicitly defined combined value
}
foreach (Permissions permission in Enum.GetValues<Permissions>())
{
Console.WriteLine(permission);
}
Output:
None
Read
Write
ReadWrite
Execute
Key Points:
Enum.GetValues
returns all defined values of the enum.Enum.GetNames
returns the names of the enum values as strings.- Use the generic method (
Enum.GetValues<T>
) in .NET 5+ for better type safety. - For flags enums, only explicitly defined values are returned (not all possible combinations).
By following these steps, you can easily enumerate all values of an enum in C#!