HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How to loop through all enum values in C#?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
enumhowvaluesallloopthrough

Problem

public enum Foos
{
    A,
    B,
    C
}


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

Basically?

foreach(Foo in Foos)

Solution

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();


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

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


Usage:

var values = EnumUtil.GetValues();

Code Snippets

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

Context

Stack Overflow Q#972307, score: 2538

Revisions (0)

No revisions yet.