Loop through all enum values

Enum loop

Sometimes it is necessary to iterate through the values of type Enum in CSharp (C#).

Iterating through enums can be done in two variants, but they are very similar. Once as an enum type and once as an integer type. Here we use foreach-loop with the following enum as an example:

Example Enumeration

public enum TimeUnit  
{  
    Seconds,  
    Minutes,  
    Hours,
    Weeks,
    Months,
    Years       
}

Variant 1: Enum-Type

In this variant, the enum values are iterated and the value is returned as a string to the console.

foreach - Loop to iterate through enum

foreach(TimeUnit e in Enum.GetValues(typeof(TimeUnit)))  
{  
 Console.WriteLine(e.ToString());   
}

Variant 2: Integer-Type

In this variant, the enum values are iterated as integer and the value is returned as an integer to console.
This variant can be useful if you want to continue working directly with the integer value.

foreach - Loop to iterate through enumeration

foreach( int i in Enum.GetValues(typeof(TimeUnit)) )
{
    Console.WriteLine(i);
}

Hinweis

GetValues() always returns the numerical values from the enumaration.

Enum.GetNames() returns the string value of the enumarion.

Werbung



comments powered by Disqus

Copyright Dunkel & Iwer GbR | Datenschutzerklärung | Impressum