Wednesday, May 9, 2018

.net - How to loop through all enum values in C#?





This question already has an answer here:
How do I enumerate an enum in C#? 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)

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


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

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...