How to enumerate an enum in C#
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);}}}
Explanation
- Lines 5–14: We formed
public enum,Days, with no initialization. According to the standards,Mondaywill be assigned a value of0, and the values ofTuesday,Wednesday, and other days will be determined by increments of 1. - Lines 18–19: We use
forEach()to call a providedEnum.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);}}}
Explanation
- Lines 5–14: We have formed
public enum,Days, with no initialization. According to the standards,Mondaywill be assigned the value0, and the values ofTuesday,Wednesday, and other days will be determined by increments of 1. - Lines 18–19: We use the
forEach()method to call a providedEnum.GetValues()function once for each element in an array in ascending index order and print the output.