Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
c#

How to enumerate an enum in C#

Mahnoor Zaheer

Overview

An Enum is a user-defined value type in C#, which represents a group of constants. It can be created in a class, structure, or namespace.

Enumerating an enum

Enumerating means we loop through the elements of an enum. There are two methods to enumerate an enum:

  • Using the Enum.GetNames() method
  • Using the Enum.GetValues() method

The Enum.GetNames() method

This approach will loop through the elements of the enum and get the names of constants from the enum to an array. After that, it uses a foreach loop to print this array.

using System;
 
public class Names
{
    public enum Days
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }
 
    public static void Main()
    {
        foreach (string day in Enum.GetNames(typeof(Days))) {
            Console.WriteLine(day);
        }
    }
}
 
The example code of enumerating an enum

Explanation

  • Lines 5–14: We formed public enum, Days, with no initialization. According to the standards, Monday will be assigned a value of 0, and the values of Tuesday, Wednesday, and other days will be determined by increments of 1.
  • Lines 18–19: We use forEach() to call a provided Enum.GetValues() function once for each element in an array in ascending index order. We then print the output.

The Enum.GetValues() method

This method takes the values of enum constants, and then we print them using the foreach loop.

using System;
 
public class Value
{
    public enum Days
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }
 
    public static void Main()
    {
        foreach (Days day in Enum.GetValues(typeof(Days))) {
            Console.WriteLine(day);
        }
    }
}
The example code of enumerating an enum using GetValues() in C#

Explanation

  • Lines 5–14: We have formed public enum, Days, with no initialization. According to the standards, Monday will be assigned the value 0, and the values of Tuesday, Wednesday, and other days will be determined by increments of 1.
  • Lines 18–19: We use the forEach() method to call a provided Enum.GetValues() function once for each element in an array in ascending index order and print the output.

RELATED TAGS

communitycreator
c#
RELATED COURSES

View all Courses

Keep Exploring