Calling a generic method with a dynamic type [duplicate]
Lets say I have the following classes
public class Animal { .... }
public class Duck : Animal { ... }
public class Cow : Animal { ... }
public class Creator
{
public List<T> CreateAnimals<T>(int numAnimals)
{
Type type = typeof(T);
List<T> returnList = new List<T>();
//Use reflection to populate list and return
}
}
Now in some code later I want to read in what animal to create.
Creator creator = new Creator();
string animalType = //read from a file what animal (duck, cow) to create
Type type = Type.GetType(animalType);
List<animalType> animals = creator.CreateAnimals<type>(5);
Now the problem is the last line isn't valid. Is there some elegant way to do this then?
Solution 1:
I don't know about elegant, but the way to do it is:
typeof(Creator)
.GetMethod("CreateAnimals")
.MakeGenericMethod(type)
.Invoke(creator, new object[] { 5 });
Solution 2:
Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.
To use reflection, you'd use Type.GetMethod
to get the method definition, then call MethodInfo.MakeGenericMethod(type)
, then invoke it like any other method.