다음을 통해 공유


Iterating Through Enum in C#

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. (Check here) At times you may want or need to iterate through the enumerator list to be used in your code, yet it is not very easy just to run a for loop or foreach loop to fetch each enumerator. This article shows you precisely how you can achieve that.

Let's assume we have the following enum usage in our code:

public enum MyEnum`` 

{

    ``Enum1,

    ``Enum2,

    ``Enum3,

    ``Enum4

}

Now to access or iterate through the enum list you can do the following:

foreach (MyEnum thisEnum in Enum.GetValues(typeof(MyEnum)))

{

    ``Console.WriteLine(thisEnum.ToString());

    ``// Or you can write your code here

}

The aforementioned code will produce the following result on the console:

Enum1

Enum2

Enum3

Enum4