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 means we loop through the elements of an enum
. There are two methods to enumerate an enum
:
Enum.GetNames()
methodEnum.GetValues()
methodEnum.GetNames()
methodThis 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);}}}
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.forEach()
to call a provided Enum.GetValues()
function once for each element in an array in ascending index order. We then print the output.Enum.GetValues()
methodThis 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);}}}
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.forEach()
method to call a provided Enum.GetValues()
function once for each element in an array in ascending index order and print the output.