How to enumerate an enum in C#?

Enumerations, commonly known as enums, are a powerful feature in C# that allows developers to define a set of named constants. While enums provide a convenient way to represent a group of related values, they can also be enumerated to access and manipulate their elements.

In this article, we’ll explore how to enumerate an enum in C# with practical examples.

Define Enum in C#

To demonstrate the process of enumeration, let’s define an enum called MyEnum with a set of values. Additionally, we’ll apply the [Flags] attribute to showcase the enumeration of flag-based enums. We’ll use this enum throughout the guide to illustrate the various methods of iterating over its elements.

enum MyEnum 
{
    Monday=1,
    Tuesday=2,
    Wednesday=3,
    Thursday=4,
    Friday=5,
    Saturday=6,
    Sunday=7
}

GetValues Method in Enum

The Enum.GetValues method is a powerful tool in C# that allows us to retrieve an array of all the values present in an enum. This method provides a straightforward way to access and iterate over the elements of an enum.

Array enumValues = Enum.GetValues(typeof(MyEnum));

In this example, MyEnum the enum type for which we want to retrieve the values. The Enum.GetValues method returns an array (enumValues) containing all the values of the specified enum.

Enumerate enumValues Using Loop

We can then iterate over the enum values using a foreach loop or any other desired iteration method.

foreach (MyEnum value in enumValues)
{
    // Perform operations on each enum value
    Console.WriteLine(value);
}

The output of the above code will be

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Enumerating Enum Flags

In some cases, enums are used to represent combinations of values using flags. To enable this behavior, you can apply the [Flags] attribute to the enum declaration. This allows bitwise operations on enum values.

 foreach (MyEnum flag in Enum.GetValues(typeof(MyEnum)))
        {
                Console.WriteLine(flag);
        }

To enumerate the individual flags within the flags value, we use the Enum.GetValues method along with the typeof(MyFlags) argument to get an array of all possible flag values. We then iterate over this array and check if the flags variable has each flag using the HasFlag method. If a flag is present, we print it to the console.

Conclusion

enumerating an enum in C# using Enum.GetValues allows you to access and work with each individual value of an enum type. It provides flexibility and convenience when dealing with enums, particularly when you need to perform operations or make decisions based on the enum values.

Scroll to Top