Reputation: 2191
I tried to convert enum to a generic List by using the following code
public static List<T> ToList<T>(Type t) where T : struct
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
it complied successfully.
and I tried to call the above mentioned method by using the following code
enum Fruit
{
apple = 1,
orange = 2,
banana = 3
};
private List<Fruit> GetFruitList()
{
List<Fruit> allFruits = EnumHelper.ToList(Fruit);
return allFruits;
}
resulted in the following error
Compiler Error Message: CS0118: 'default.Fruit' is a 'type' but is used like a 'variable'
So I am sure how to pass Enum type as a argument.
Upvotes: 1
Views: 4248
Reputation: 186
why not just do this:
public static List<T> ToList<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
Upvotes: 4
Reputation: 17837
public static List<T> ToList<T>() where T : struct
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
enum Fruit
{
apple = 1,
orange = 2,
banana = 3
};
private List<Fruit> GetFruitList()
{
List<Fruit> allFruits = EnumHelper.ToList<Fruit>();
return allFruits;
}
Upvotes: 8
Reputation: 61427
Use EnumHelper.ToList<Fruit>(typeof(Fruit));
. However, you can lose the parameter, declare as EnumHelper.ToList<T>()
and use it EnumHelper.ToList<Fruit>()
.
Upvotes: 1
Reputation: 80714
Loose the argument Type t
The type is already being passed as generic parameter, so you don't need a regular argument for the method.
Upvotes: 1
Reputation: 9303
In order to pass a Type
to your function, you should use the following syntax:
EnumHelper.ToList(typeof(Fruit));
Upvotes: 0