NeuroAgent

How to Loop Through Enum Values in C#

Learn the proper way to iterate through all enum values in C#. Discover Enum.GetValues() methods, performance optimizations, and complete examples with code snippets.

Question

How to loop through all enum values in C#

Given the following enum:

csharp
public enum Foos
{
    A,
    B,
    C
}

What is the proper way to iterate through all possible values of the Foos enum? I’m looking for a solution similar to:

csharp
foreach(Foo in Foos)
NeuroAgent

The proper way to iterate through all possible values of the Foos enum in C# is to use the Enum.GetValues() method with a foreach loop. Here’s the correct syntax:

csharp
foreach (var foo in Enum.GetValues(typeof(Foos)))
{
    // Code to process each enum value
}

Contents

Basic Enum.GetValues Approach

The most straightforward method to iterate through all enum values is using Enum.GetValues() with a foreach loop. This method returns an array containing all the values of the specified enum type.

csharp
public enum Foos
{
    A,
    B,
    C
}

// Basic approach
foreach (Foo foo in Enum.GetValues(typeof(Foos)))
{
    Console.WriteLine(foo);
}

According to the Stack Overflow community, this is the recommended approach for iterating through enum values. The Enum.GetValues() method in the System.Enum class retrieves an array of the constant values of the specified enum.

Generic vs Non-Generic Methods

C# provides both generic and non-generic versions of the GetValues method:

Generic Approach (C# 3.5+)

csharp
// Generic approach - type-safe and cleaner
foreach (var foo in Enum.GetValues<Foos>())
{
    Console.WriteLine(foo);
}

The generic approach [Enum.GetValues<TEnum>()](https://www.tutorialsteacher.com/articles/how-to-loop-through-enum-in-csharp) is more type-safe and cleaner to use. This static method retrieves an array of the constant values of the specified enum type.

Non-Generic Approach

csharp
// Non-generic approach - works in older C# versions
Array values = Enum.GetValues(typeof(Foos));
foreach (var foo in values)
{
    Console.WriteLine(foo);
}

Getting Enum Names

If you need to work with the string names of enum values instead of the values themselves, use Enum.GetNames():

csharp
// Get enum names
foreach (string name in Enum.GetNames(typeof(Foos)))
{
    Console.WriteLine(name);
}

As shown in the Tutlane tutorial, this approach returns the string names of all enum members, which can be useful when you need to work with the textual representations of your enum values.

Performance Considerations

While Enum.GetValues() is convenient, it does involve reflection and creates a new array each time it’s called. For performance-critical scenarios, consider these optimizations:

Caching the Values

csharp
// Cache the values for better performance
private static readonly Foos[] FooValues = (Foos[])Enum.GetValues(typeof(Foos));

// Use cached values
foreach (var foo in FooValues)
{
    Console.WriteLine(foo);
}

Using FastEnum Library

For high-performance scenarios, consider using the FastEnum library, which provides optimized enum utilities:

csharp
// FastEnum approach - significantly faster
var values = FastEnum.GetValues<Foos>();
foreach (var foo in values)
{
    Console.WriteLine(foo);
}

According to the FastEnum documentation, this library significantly improves performance for enum operations compared to the standard System.Enum methods.

Performance Comparison

The Stack Overflow discussion on enum performance shows that while using Enum.GetValues() is fine for most applications, performance-sensitive code might benefit from pre-computing values or using alternative approaches like dictionaries.

Alternative Approaches

Using LINQ

csharp
// Using LINQ for additional flexibility
foreach (var foo in Enum.GetValues(typeof(Foos)).Cast<Foos>())
{
    Console.WriteLine(foo);
}

For Loop with Index

csharp
// For loop approach when you need index access
var values = Enum.GetValues<Foos>();
for (int i = 0; i < values.Length; i++)
{
    var foo = values[i];
    Console.WriteLine($"Index {i}: {foo}");
}

As mentioned in PietschSoft’s article, using a for loop enables you to perform operations based on the index of enum values, which can be useful in certain scenarios.

Complete Examples

Example 1: Basic Usage

csharp
public enum Foos
{
    A,
    B,
    C
}

public static void Main()
{
    // Method 1: Generic approach
    Console.WriteLine("Using Enum.GetValues<Foos>():");
    foreach (var foo in Enum.GetValues<Foos>())
    {
        Console.WriteLine(foo);
    }

    // Method 2: Non-generic approach
    Console.WriteLine("\nUsing Enum.GetValues(typeof(Foos)):");
    foreach (var foo in Enum.GetValues(typeof(Foos)))
    {
        Console.WriteLine(foo);
    }
}

Example 2: Getting Values and Names

csharp
public static void PrintEnumInfo<T>() where T : Enum
{
    Console.WriteLine($"Enum Type: {typeof(T).Name}");
    
    Console.WriteLine("\nValues:");
    foreach (var value in Enum.GetValues<T>())
    {
        Console.WriteLine($"  {value} = {(int)value}");
    }
    
    Console.WriteLine("\nNames:");
    foreach (var name in Enum.GetNames<T>())
    {
        Console.WriteLine($"  {name}");
    }
}

// Usage
PrintEnumInfo<Foos>();

Example 3: Performance-Optimized Version

csharp
public static class EnumHelper<T> where T : Enum
{
    private static readonly T[] Values = (T[])Enum.GetValues(typeof(T));
    
    public static IEnumerable<T> GetValues() => Values;
    
    public static T[] GetValuesArray() => Values;
}

// Usage
foreach (var foo in EnumHelper<Foos>.GetValues())
{
    Console.WriteLine(foo);
}

Sources

  1. How to loop through all enum values in C# - Stack Overflow
  2. How to loop through an enum in C#? - TutorialTeacher
  3. Looping Through Enums in C# - Medium
  4. C#: How to Enumerate over Enum values and names - Chris Pietschmann
  5. How to loop through all enum values in C# - net-informations.com
  6. How to loop or get enum names and values in C# - ArunGudelli
  7. C# Enum (Enumerator) - Tutlane
  8. FastEnum : The world fastest enum utility for C#/.NET - Medium
  9. Enums parsing performance - Mariusz Wojcik
  10. C# Iterating through an enum? - Stack Overflow

Conclusion

Iterating through enum values in C# is straightforward using Enum.GetValues(), but there are several important considerations:

  • Use the generic approach (Enum.GetValues<T>()) whenever possible for better type safety and cleaner code
  • Cache the values if you’re iterating frequently in performance-critical scenarios
  • Consider FastEnum for high-performance applications that require extensive enum operations
  • Use Enum.GetNames() when you need the string representations of enum values
  • Choose the right iteration method based on your specific needs - foreach for simplicity, for loop for index access, or LINQ for complex operations

The most important takeaway is that there’s no single “perfect” method - the best approach depends on your specific requirements for type safety, performance, and code readability. For most everyday scenarios, Enum.GetValues<T>() with a foreach loop provides the best balance of simplicity and performance.