How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
enum
types are called "enumeration types" not because they are containers that "enumerate" values (which they aren't), but because they are defined by enumerating the possible values for a variable of that type.
(Actually, that's a bit more complicated than that - enum types are considered to have an "underlying" integer type, which means each enum value corresponds to an integer value (this is typically implicit, but can be manually specified). C# was designed in a way so that you could stuff any integer of that type into the enum variable, even if it isn't a "named" value.)
The System.Enum.GetNames method can be used to retrieve an array of strings which are the names of the enum values, as the name suggests.
EDIT: Should have suggested the System.Enum.GetValues method instead. Oops.
foreach (Suit suit in Enum.GetValues(typeof(Suit))) { }
I've heard vague rumours that this is terifically slow. Anyone know? – Orion Edwards Oct 15 '08 at 1:31 7
I think caching the array would speed it up considerably. It looks like you're getting a new array (through reflection) every time. Rather:
Array enums = Enum.GetValues(typeof(Suit));
foreach (Suit suitEnum in enums)
{
DoSomething(suitEnum);
}
That's at least a little faster, ja?
Here is a working example of creating select options for a DDL:
var resman = ViewModelResources.TimeFrame.ResourceManager;
ViewBag.TimeFrames = from MapOverlayTimeFrames timeFrame
in Enum.GetValues(typeof(MapOverlayTimeFrames))
select new SelectListItem
{
Value = timeFrame.ToString(),
Text = resman.GetString(timeFrame.ToString()) ?? timeFrame.ToString()
};
Some versions of the .NET framework do not support Enum.GetValues
. Here's a good workaround from Ideas 2.0: Enum.GetValues in Compact Framework:
public Enum[] GetValues(Enum enumeration)
{
FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
Enum[] enumerations = new Enum[fields.Length];
for (var i = 0; i < fields.Length; i++)
enumerations[i] = (Enum) fields[i].GetValue(enumeration);
return enumerations;
}
As with any code that involves reflection, you should take steps to ensure it runs only once and results are cached.
public void PrintAllSuits()
{
foreach(string suit in Enum.GetNames(typeof(Suits)))
{
Console.WriteLine(suit);
}
}
Add method public static IEnumerable<T> GetValues<T>()
to your class, like:
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
Call and pass your enum. Now you can iterate through it using foreach
:
public static void EnumerateAllSuitsDemoMethod()
{
// Custom method
var foos = GetValues<Suit>();
foreach (var foo in foos)
{
// Do something
}
}