How to loop through all enum values in C#?

C#.NetEnumsLanguage Features

C# Problem Overview


> This question already has an answer here:
> https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum 26 answers

public enum Foos
{
    A,
    B,
    C
}

Is there a way to loop through the possible values of Foos?

Basically?

foreach(Foo in Foos)

C# Solutions


Solution 1 - C#

Yes you can use the ‍GetValue‍‍‍s method:

var values = Enum.GetValues(typeof(Foos));

Or the typed version:

var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();

I long ago added a helper function to my private library for just such an occasion:

public static class EnumUtil {
    public static IEnumerable<T> GetValues<T>() {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }
}

Usage:

var values = EnumUtil.GetValues<Foos>();

Solution 2 - C#

foreach(Foos foo in Enum.GetValues(typeof(Foos)))

Solution 3 - C#

foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
   Console.WriteLine(val);
}

Credit to Jon Skeet here: http://bytes.com/groups/net-c/266447-how-loop-each-items-enum

Solution 4 - C#

foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    ...
}

Solution 5 - C#

UPDATED
Some time on, I see a comment that brings me back to my old answer, and I think I'd do it differently now. These days I'd write:

private static IEnumerable<T> GetEnumValues<T>()
{
    // Can't use type constraints on value types, so have to do check like this
    if (typeof(T).BaseType != typeof(Enum))
    {
        throw new ArgumentException("T must be of type System.Enum");
    }

    return Enum.GetValues(typeof(T)).Cast<T>();
}

Solution 6 - C#

static void Main(string[] args)
{
    foreach (int value in Enum.GetValues(typeof(DaysOfWeek)))
    {
        Console.WriteLine(((DaysOfWeek)value).ToString());
    }
    
    foreach (string value in Enum.GetNames(typeof(DaysOfWeek)))
    {
        Console.WriteLine(value);
    }
    Console.ReadLine();
}

public enum DaysOfWeek
{
    monday,
    tuesday,
    wednesday
}

Solution 7 - C#

 Enum.GetValues(typeof(Foos))

Solution 8 - C#

Yes. Use GetValues() method in System.Enum class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondivinciView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#SLaksView Answer on Stackoverflow
Solution 3 - C#InisheerView Answer on Stackoverflow
Solution 4 - C#adrianbanksView Answer on Stackoverflow
Solution 5 - C#Neil BarnwellView Answer on Stackoverflow
Solution 6 - C#dbonesView Answer on Stackoverflow
Solution 7 - C#Vasu BalakrishnanView Answer on Stackoverflow
Solution 8 - C#Pablo Santa CruzView Answer on Stackoverflow