HomeComputer programmingHow to Loop through Enum Values in C#

How to Loop through Enum Values in C#

Looping through an enumeration list or enum in C# is an essential skill. This tech-recipe provides a detailed example and walks through an explanation of the looping process.

The enumeration data type (or enum) is used to assign symbolic constants with unique values. The enum keyword is use in C# to declare an enumeration.

First, an enum will need to be declared using the following syntax:

enum identifier { enumerator-list }

Using this syntax we can build our example.

enum WeekDays { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

In above example the first symbolic constant ‘Sun’ will be assigned a value 0. ‘Mon’ will equal 1. This pattern would continue until ‘Sat’ equals the value of 6. Now, without looping, printing all the enum list items and their respective values could require up to seven lines of code. One for each day of the week.

int val1 = (int)WeekDays.Sun;
int val2 = (int)WeekDays.Mon;
...
int val7 = (int)WeekDays.Sat;

Obviously, this is an awkward solution if the enumeration list is huge. It is much easier to loop through enumeration list to print the symbolic constants and the associated values.

The Enum.Getnames and Enum.GetValues methods are used to retrieve the symbolic-constant and values associated with it. The basic syntax of these methods is the following:

var values = Enum.GetValues(typeof(MyEnum));

Here is my working example demonstrating these methods in action.


class Program
{
enum WeekDays {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
static void Main(string[] args)
{
string[] days = Enum.GetNames(typeof(WeekDays));
foreach (string s in days)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat


class Program
{
enum WeekDays { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main(string[] args)
{
foreach (WeekDays day in Enum.GetValues(typeof(WeekDays)))
{
int x = (int)day;
Console.WriteLine("{0} = {1}", day, x);
}
Console.ReadLine();
}
}
output:
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6


class Program
{
enum WeekDays { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main(string[] args)
{
foreach (WeekDays day in Enum.GetValues(typeof(WeekDays)))
{
int x = (int)day;
Console.Write("{0}\t", x);
}
Console.ReadLine();
}
}
Output
0       1       2       3       4       5       6

Vishwanath Dalvi
Vishwanath Dalvi
Vishwanath Dalvi is a gifted engineer and tech enthusiast. He enjoys music, magic, movies, and gaming. When not hacking around or supporting the open source community, he is trying to overcome his phobia of dogs.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!