Reputation: 11
I'd like to know how to list the values of an enum when the Enum is passed in as a generic parameter. The below code is my attempt at this. My hope was that the loop in the ListReturnTypeValues method would cycle through the values Red, Blue, Green, but the code fails.
public enum Colour
{
Red,
Blue,
Green
}
class Program
{
static void Main(string[] args)
{
ListReturnTypeValues(i => (Colour)i);
}
static void ListReturnTypeValues(Func<int, Enum> func)
{
foreach(var i in Enum.GetValues(func.Method.ReturnType))
{
//Cycle through Red, Blue, Green...
}
}
}
Upvotes: 0
Views: 51
Reputation: 11
With inspiration from @TheGeneral's Comment, I was able to find a working solution:
public enum Colour
{
Red,
Blue,
Green
}
class Program
{
static void Main(string[] args)
{
ListReturnTypeValues(i => (Colour)i);
}
static void ListReturnTypeValues<T>(Func<int, T> func) where T : Enum
{
foreach(var i in Enum.GetValues(typeof(T)))
{
//Cycle through Red, Blue, Green...
}
}
}
Thanks everyone!
Upvotes: 1