I have a method that is designed to accept a List in it's declaration as follows:
public class MyHandler
{
public T LookUp<T>()
{
//This method compiles and returns a dynamically typed List
...
}
}
I call this method from elsewhere as such:
MyHandler mh = new MyHandler();
List<AgeGroup> ageGroups = mh.LookUp<List<AgeGroup>>();
This process works great, but I am looking for a way of being able to dynamically load the AgeGroup type from a string.
I have found examples like this, but am not able to work out how to implement it in this case. For example, I have tried the following (and does not compile):
Type t = Assembly.Load("MyNamespace").GetType("MyNamespace.AgeGroup");
List<t> ageGroups = mh.LookUp<List<t>>();
I also tried using typeof(t), but to no avail. Any ideas?
You can construct a generic type at runtime like this:
Type listType = typeof(List<>);
Type typeArg = Assembly.Load("MyNamespace").GetType("MyNamespace.AgeGroup");
listType = listType.MakeGenericType(typeArg);
IList list = (IList)Activator.CreateInstance(listType);
Of course you won't be able to use it as a List<AgeGroup> unless you know the type parameter at compile time. You also won't be able to use Lookup<T> like you did in your example unless you know the type at compile time. You'd have to invoke it like this:
MethodInfo lookupMethod = mh.GetType().GetMethod("LookUp");
lookupMethod = lookupMethod.MakeGenericMethod(listType);
lookupMethod.Invoke(mh, null);
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