views:

80

answers:

2

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, 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.

+1  A: 

For whatever reason, the instance of SomeClass returned by GetClass, even after the types have been resolved, doesn't allow you to call the GetStuff method.

The bottom line is that you should simply construct SomeClass first and then invoke the method. Like this:

typeof(SomeClass<>)
    .MakeGenericType(StuffType)
    .GetMethod("GetStuff")
    .Invoke(lSomeClassInstance, null);
Andre Luus
A: 

Just a copy-paste. You can not mark your post as the answer, so you can mark mine :).

typeof(SomeClass<>) 
    .MakeGenericType(StuffType) 
    .GetMethod("GetStuff") 
    .Invoke(lSomeClassInstance, null); 
Amby