How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
If you need speed and type checking at build and run time, this helper method is better than using LINQ to cast each element:
public static T[] GetEnumValues() where T : struct, IComparable, IFormattable, IConvertible
{
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException(string.Format("{0} is not of type System.Enum", typeof(T)));
}
return Enum.GetValues(typeof(T)) as T[];
}
And you can use it like below:
static readonly YourEnum[] _values = GetEnumValues();
Of course you can return IEnumerable
, but that buys you nothing here.