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.
public enum SocialNetworks { Facebook, Linkedin, Twitter, Instagram };
class Program
{
static void Main(string[] args)
{
foreach (var name in Enum.GetNames(typeof(SocialNetworks)))
{
Console.WriteLine(name);
}
}
}
public enum SocialNetworks { Facebook, Linkedin, Twitter, Instagram };
class Program
{
static void Main(string[] args)
{
foreach (var name in Enum.GetNames<SocialNetworks>())
{
Console.WriteLine(name);
}
}
}
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.
public enum SocialNetworks { Facebook = 3, Linkedin = 4, Twitter = 5, Instagram = 8};
class Program
{
static void Main(string[] args)
{
foreach (var val in Enum.GetValues(typeof(SocialNetworks))
{
Console.WriteLine((int)val);
}
}
}
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);
}
}
}
0 1 2 3