How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
If enum values range strictly from 0 to n - 1, a generic alternative is:
public void EnumerateEnum()
{
int length = Enum.GetValues(typeof(T)).Length;
for (var i = 0; i < length; i++)
{
var @enum = (T)(object)i;
}
}
If enum values are contiguous and you can provide the first and last element of the enum, then:
public void EnumerateEnum()
{
for (var i = Suit.Spade; i <= Suit.Diamond; i++)
{
var @enum = i;
}
}
But that's not strictly enumerating, just looping. The second method is much faster than any other approach though...