Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 
like image 565
divinci Avatar asked Jun 09 '09 20:06

divinci


2 Answers

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>(); 
like image 195
JaredPar Avatar answered Sep 17 '22 17:09

JaredPar


foreach(Foos foo in Enum.GetValues(typeof(Foos))) 
like image 35
SLaks Avatar answered Sep 19 '22 17:09

SLaks