C#: How to Enumerate over Enum values and names

May 3, 2024  • C#

When it comes to working with enums in C#, there are various methods to enumerate through their values, each with its own advantages and use cases. In this article, we’ll look at a few different techniques for enumerating enums in C#.

To start, let’s look at the following enum in C#, that will be referenced in each example:

public enum AnimalEnum
{
  Tiger,
  Bear,
  Human,
  Snake
}

Enumerate C# Enum using foreach Loop

The simplest method to iterate over enum values is by using a foreach loop with the combination of the Enum.GetValues<T>() method.

This approach is straightforward and easy to understand. Here’s how it works:

foreach (var animalValue in Enum.GetValues<AnimalEnum>())
{
  obj.AnimalType = (AnimalEnum)animalValue;
  // do something here
}

This method iterates through all the values of the enum Animal, after the Enum.GetValues<T>() method returns an Array of the Enum values.

Enumerate C# Enum using for Loop

If you need more control over the iteration process, you can use a for loop.

This approach allows you to access individual enum values by their index:

var animalValues = Enum.GetValues<AnimalEnum>();
fo(int i = 0; i < animalValues.length; i++)
{
  var value = (AnimalEnum)i;
  // do something here
}

Using a for loop enables you to perform operations based on the index of enum values.

Enumerate C# Enum using foreach by Enum Names

If you only need the names of enum values without their underlying integer representations, you can use Enum.GetNames:

foreach(var name in Enum.GetNames(typeof(AnimalEnum)))
{
  // do something here
  var value = Enum.Parse<AnimalEnum>(name, true);
}

This method is useful when you only need the names of enum values and may not always require their corresponding integer values.

Notice, the Enum.Parse<T>(value, ignoreCase) method is being used to get the value for the enum based on the name. This can be valuable if only the name is known, but the value needs to be determined. The second argument on the method tells the method whether to be case sensitive on matching the name to a value; true means to ignore case.

Enumerate C# Enum using LINQ

LINQ (Language Integrated Query) provides a concise and expressive way to manipulate collections, including enums.

You can use LINQ to iterate over enum values and perform filtering or mapping operations using the LINQ .Where() or .Select() methods:

var enumValues = Enum.GetValues(typeof(AnimalEnum)).Cast<AnimalEnum>();
foreach (var value in enumValues.Where(x => x != MyEnum.SomeValue))
{
  // so something here
}

Using LINQ allows for more complex operations on enum values, such as filtering or projection.

Enhancing Enum Tasks using Extension Methods

For common tasks that get repeated in the code, you can write an extension method to make the enumeration task easier. This way you can add your own extension on the Enum you’re working with to make the code easier to reuse and read.

For example, if it’s common to convert the value of the Enum to the Name, then an extension method like the following may make the code easier to reuse:

public static class AnimalEnumExtensions
{
  public static string? GetName(this AnimalEnum value)
  {
    return Enum.GetName(typeof(AnimalEnum), value);
  }
}

Then, this extension method can be used like this:

AnimalEnum value = AnimalEnum.Bear;
string? name = value.GetName();

More Reading: To read more about creating extension methods to enhance the usability of Enums in C#, go read the “C#: Enhance Enums using Extension Methods” article.

Conclusion

Enumerating through enum values in C# offers flexibility and versatility, allowing developers to choose the method that best suits their requirements. Whether it’s a simple foreach loop, a more controlled for loop, leveraging LINQ for advanced operations, or extracting only enum names, C# provides several options for efficiently working with enums.

Understanding these different enumeration techniques empowers developers to write cleaner and more maintainable code when dealing with enums in C#. By selecting the appropriate method based on the specific use case, developers can enhance code readability and improve overall software quality.