How to invoke a method with a generic return type using reflection
Posted
by Andre Luus
on Stack Overflow
See other posts from Stack Overflow
or by Andre Luus
Published on 2010-06-08T09:37:53Z
Indexed on
2010/06/08
9:42 UTC
Read the original article
Hit count: 237
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.
© Stack Overflow or respective owner