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
- How to get the sizeof a datatype in C#?
- Difference between String and StringBuilder in C#
- Static vs Singleton in C#
- Difference between == and Equals() Method in C#
- Asynchronous programming with async, await, Task in C#
- Generate Random Numbers in C#
- Difference between Two Dates in C#
- Convert int to enum in C#
- BigInteger Data Type in C#
- Convert String to Enum in C#
- Convert an Object to JSON in C#
- Convert JSON String to Object in C#
- DateTime Formats in C#
- How to convert date object to string in C#?
- Compare strings in C#
- How to count elements in C# array?
- Difference between String and string in C#.
- How to get a comma separated string from an array in C#?
- Boxing and Unboxing in C#
- How to convert string to int in C#?