How to invoke a method with a generic return type using reflection
- by Andre Luus
Hi there!
I'm trying to invoke a method with reflection that has a generic return type, like this:
public class SomeClass<T>
{
public List<T> GetStuff();
}
I get an instance of SomeClass with a call to a Repository's GetClass<T> generic method.
MethodInfo lGetSomeClassMethodInfo = typeof(IRepository)
.GetMethod("GetClass")
.MakeGenericMethod(typeof(SomeClass<>);
object lSomeClassInstance = lGetSomeClassMethodInfo.Invoke(
lRepositoryInstance, null);
After that, I this is where I try to invoke the GetStuff method:
typeof(SomeClass<>).GetMethod("GetStuff").Invoke(lSomeClassInstance, null)
I get an exception about the fact that the method has generic arguments. However, I can't use MakeGenericMethod to resolve the return type. Also, if instead of typeof(SomeClass<>) I use lSomeClassInstance.GetType() (which should have resolved types) GetMethod("GetStuff") returns null!
UPDATE
I have found the solution and will post the answer shortly.