How to Loop Through an Enum in C#: A Beginner's Guide

Category > CSHARP || Published on : Friday, March 10, 2023 || Views: 403 || C# enum loop through enum programming beginner's guide


Enumerations, or enums, are an essential part of programming languages like C#. They represent a set of named constants, which can make your code more organized and readable. Looping through an enum allows you to perform a set of actions on each of the enum's named constants, and it's a skill that every C# programmer should know.

In C#, an enum is a value type that represents a set of named constants. Looping through an enum allows you to perform a set of actions on each of the enum's named constants. In this article, we will explore how to loop through an enum in C# with the help of example codes.

Defining an Enum To begin with, let's define an enum in C#. Here's an example:

enum DaysOfWeek
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

In the above code, we have defined an enum named "DaysOfWeek" which contains seven named constants representing each day of the week.

Looping through an Enum There are several ways to loop through an enum in C#. Let's take a look at each of them:

1. Using a foreach loop You can use a foreach loop to loop through an enum as shown below:

foreach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek)))
{
    Console.WriteLine(day);
}

In the above code, we use the Enum.GetValues method to get an array of all the named constants in the DaysOfWeek enum. We then use a foreach loop to iterate over each of these named constants and print it to the console.

2. Using a for loop Another way to loop through an enum is to use a for loop as shown below:

for (int i = 0; i < Enum.GetNames(typeof(DaysOfWeek)).Length; i++)
{
    DaysOfWeek day = (DaysOfWeek)i;
    Console.WriteLine(day);
}

In the above code, we use the Enum.GetNames method to get an array of all the names of the named constants in the DaysOfWeek enum. We then use a for loop to iterate over each of these names, convert it to its corresponding named constant using casting, and print it to the console.

Conclusion In this article, we explored how to loop through an enum in C#. We learned that we can use a foreach loop or a for loop to iterate over each of the named constants in the enum. We also provided examples of each of these methods. By using these techniques, you can easily perform a set of actions on each of the named constants in your enum.