How to loop through an enum in C#?


Here you will learn how to enumerate or loop through an enum.

In C#, an enum is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays.Monday is more readable than number 0 when referring to the day in a week.

An enum can be looped through using Enum.GetNames<TEnum>(), Enum.GetNames(), Enum.GetValues<TEnum>(), or Enum.GetValues() static methods with the foreach loop.

The following example gets the names of an enum using the Enum.GetNames<TEnum>() method.

Example: Loop through Enum Member Names
public enum SocialNetworks { Facebook, Linkedin, Twitter, Instagram };

class Program
{
    static void Main(string[] args)
    {
        foreach (var name in Enum.GetNames<SocialNetworks>())
        {
            Console.WriteLine(name);
        }
    }
}
Output:
Facebook
Linkedin
Twitter
Instagram

The Enum.GetValues<TEnum>() is a static method that retrieves an array of the constant values of the specified enum.

The following example shows how to get the values of an enum using the Enum.GetValues<TEnum>() method.

Example: Loop through Enum Values
public enum SocialNetworks {  Facebook = 3, Linkedin = 4, Twitter = 5, Instagram = 8};

class Program
{
    static void Main(string[] args)
    {
        foreach (var val in Enum.GetValues<SocialNetworks>())
        {
            Console.WriteLine((int)val);
        }
    }
}
Output:
0
1
2
3