Tuesday, January 8, 2019

How to loop through all enum values in C#? [duplicate]


public enum Foos
{
    A,
    B,
    C
}
Is there a way to loop through the possible values of Foos?
Basically?
foreach(Foo in Foos)

Answer:

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

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...