How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
I think this is more efficient than other suggestions because GetValues()
is not called each time you have a loop. It is also more concise. And you get a compile-time error, not a runtime exception if Suit
is not an enum
.
EnumLoop.ForEach((suit) => {
DoSomethingWith(suit);
});
EnumLoop
has this completely generic definition:
class EnumLoop where Key : struct, IConvertible {
static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
static internal void ForEach(Action act) {
for (int i = 0; i < arr.Length; i++) {
act(arr[i]);
}
}
}