Question
I want to create a method that takes in an Enum
type, and returns all it's members in an array, How to create such a function?
Take for example, I have these two enums:
public enum Family
{
Brother,
Sister,
Father
}
public enum CarType
{
Volkswagen,
Ferrari,
BMW
}
How to create a function GetEnumList
so that it returns
{Family.Brother, Family.Sister, Family.Father}
for the first case.{CarType.Volkswagen, CarType.Ferrari, CarType.BMW}
for the second case.
I tried :
private static List<T> GetEnumList<T>()
{
var enumList = Enum.GetValues(typeof(T))
.Cast<T>().ToList();
return enumList;
}
But I got an InvalidOperationException
:
System.InvalidOperationException : Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true. at System.Reflection.RuntimeMethodInfo.ThrowNoInvokeException() at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
Edit: The above code is working fine-- the reason I got an exception was because profiler caused me the bug. Thank you all for your solutions.
Solution
Here is the full code:
public enum Family
{
Brother,
Sister,
Father
}
public enum CarType
{
Volkswagen,
Ferrari,
BMW
}
static void Main(string[] args)
{
Console.WriteLine(GetEnumList<Family>());
Console.WriteLine(GetEnumList<Family>().First());
Console.ReadKey();
}
private static List<T> GetEnumList<T>()
{
T[] array = (T[])Enum.GetValues(typeof(T));
List<T> list = new List<T>(array);
return list;
}
OTHER TIPS
(Family[])Enum.GetValues(typeof(Family))
Like this?
private static List<string> GetEnumList<T>()
{
return Enum.GetNames( typeof( T ) )
.Select(s => typeof(T).Name + "." + s).ToList();
}