Logo

How to loop through all enum values in C#?

Below are the main ways to loop through all values in a C# enum, along with some tips and best practices.

Using Enum.GetValues()

A common approach is to call Enum.GetValues() on the enum type:

public enum Colors { Red, Green, Blue } public void PrintAllColors() { foreach (Colors color in Enum.GetValues(typeof(Colors))) { Console.WriteLine(color); } }
  • How it Works:
    Enum.GetValues(typeof(Colors)) returns an Array of the defined values. In this case, it will yield Colors.Red, Colors.Green, and Colors.Blue.

  • Casting:
    The returned values are of type object, so you cast them back to the enum type ((Colors)) if you need strongly typed access.

Converting to a List or Array

Sometimes you want a strongly typed array or list for further processing:

var allColorsArray = (Colors[])Enum.GetValues(typeof(Colors)); var allColorsList = new List<Colors>(allColorsArray); foreach (var color in allColorsList) { Console.WriteLine(color); }
  • Why Convert:
    It can be useful to store or filter these values later in your code.

Practical Uses

  • Populate UI Controls: For instance, filling a dropdown or combo box with enum values.
  • Switch Case Testing: Iterating over all possible enum values to ensure coverage in test scenarios.
  • Logging or Debugging: Printing out or inspecting all possible states.

Best Practices

  1. Define Meaningful Names: Enums are easiest to iterate over and understand when they have descriptive names (e.g., DaysOfWeek.Monday, DaysOfWeek.Tuesday, etc.).
  2. Avoid Changing Underlying Values: If you explicitly set numeric values, be consistent and don’t reorder them—this can lead to confusion when iterating.
  3. [Flags] Enums: For enums marked with [Flags], iterating over individual values might need special consideration since a single variable can contain multiple combined flags.

Level Up Your C# & Coding Skills

If you want to enhance your coding fundamentals and tackle more complex interview questions, consider these resources at DesignGurus.io:

These courses help refine your problem-solving strategies and build confidence for technical interviews. For additional insights on coding interviews, system design, and more, head over to the DesignGurus.io YouTube channel.

In short, Enum.GetValues() is the go-to method for enumerating all enum values in C#. Whether you store them in a list, display them to a user, or test them in your code, the approach remains simple, idiomatic, and efficient.

CONTRIBUTOR
TechGrind