How to enumerate an enum in C#?

Post author: Adam VanBuskirk
Adam VanBuskirk
5/13/23 in
Tech
C#

In C#, an enum is a value type that allows you to define a set of named constant values. Enumerations are often used to define a list of related named values, such as the days of the week or the directions on a compass.

To enumerate an enum in C#, you can use the Enum.GetValues method to get an array of all the values in the enumeration. You can then iterate over this array to process each value.

Here’s an example of how to enumerate an enum in C#:

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

class Program
{
    static void Main(string[] args)
    {
        // Get an array of all the values in the DaysOfWeek enumeration
        DaysOfWeek[] days = (DaysOfWeek[])Enum.GetValues(typeof(DaysOfWeek));

        // Iterate over the array and print each value
        foreach (DaysOfWeek day in days)
        {
            Console.WriteLine(day);
        }
    }
}

In this example, we define an enum called DaysOfWeek with seven named values. We then use the Enum.GetValues method to get an array of all the values in the DaysOfWeek enumeration, and we iterate over the array using a foreach loop to print each value to the console.

The output of this program will be:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Note that the Enum.GetValues method returns an Array object, which needs to be cast to the appropriate enum type before it can be used as an array of enum values. In this example, we cast the Array object to a DaysOfWeek array.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *


Read Next




© 2024 Menyu LLC