1786
public enum Foos
{
    A,
    B,
    C
}

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

Basically?

foreach(Foo in Foos)
1
  • 3
    Since .NET 5 there is a generic version of Enum.GetValues<TEnum>(): var values = Enum.GetValues<Foos>(); Commented May 17, 2024 at 14:37

8 Answers 8

2536

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>();
Sign up to request clarification or add additional context in comments.

16 Comments

You can cast the array directly: (T[])Enum.GetValues(typeof(T))
The good thing about @ŞafakGür's comment is that (1) you don't have to go through an extra iterator (.Cast<Foos>), and (2) you don't need to box all the values and unbox them again. Şafak's cast will remain valid as long as they don't change the array type returned to some other type (like object[]). But we can be completely sure they won't because (a) it would lose performance, (b) there are already millions of codelines using Şafak's cast, and they would all break with a runtime exception.
Of course, how many enums are going to contain more than a dozen or two values? I imagine that in most cases boxing/unboxing is a negligible hit, so the cleanest solution is the highest priority.
@JCoombs I find this clean enough: public static IReadOnlyList<T> GetValues<T>() { return (T[])Enum.GetValues(typeof(T)); }. But yeah, performance difference is negligible in common usage. I just don't like the idea of creating an iterator when I already have an iterable (enumerable) object to return.
Unfortunately, this does not answer the question posed. The question was how to loop through the values of an enum. SLaks answered the question.
|
961
foreach(Foos foo in Enum.GetValues(typeof(Foos)))

5 Comments

This is a great solution. By using "Foos" instead of "var" the type inference system was able to use the right version of GetValues which returned the correct object type. Nice!
@RobertPatterson By using Foos nothing is magically inferred. It is an explicit cast.
@daveD I'd like to think people can handle writing a foreach block on their own.
@RobertPatterson var works here, in 2019.
that is very good
155
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

Comments

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

1 Comment

Repeative answer dear @arian
47

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

5 Comments

Why is using LINQ "more correct"? Please c.f. You can cast the array directly: (T[])Enum.GetValues(typeof(T)) @SafakGür, this version has less overhead IMO.
make it simple GetEnumValues<T>() where T : Enum
@SaboorAwan is not possible to use System.Enum as a type parameter constraint. Compiler says: Constraint cannot be special class 'Enum'
Yes that's why I have that comment and type checking thing in my implementation; I'd already thought of that. :)
Quick note. In C# 7.3 you can now use Enum (as well as unmanaged and delegate) as generic constraints.
42
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
}

1 Comment

16

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

1 Comment

And if you're using .net5, it comes with a generic version out of the box. i.e. no more typeof() and casting required as per most of the above examples. stackoverflow.com/a/65103244/227110
14
 Enum.GetValues(typeof(Foos))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.