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.
To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) . The Object.
To get all values of an enum, we can use the Enum. GetValues static method. The Enum. GetValues method returns an array of all enum values.
Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.
The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With