3

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?

1

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Works brilliantly! Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.