How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
My solution works in .NET Compact Framework (3.5) and supports type checking at compile time:
public static List GetEnumValues() where T : new() {
T valueType = new T();
return typeof(T).GetFields()
.Select(fieldInfo => (T)fieldInfo.GetValue(valueType))
.Distinct()
.ToList();
}
public static List GetEnumNames() {
return typeof (T).GetFields()
.Select(info => info.Name)
.Distinct()
.ToList();
}
T valueType = new T()
, I'd be happy to see a solution.A call would look like this:
List result = Utils.GetEnumValues();