1

With this code:

World w = new World();
var data = GetData<World>(w);

If I get w with reflection and this can be of type World, Ambient, Domention, etc.

How can I get GetData ???

I only have the instance object:

var data = GetData<???>(w);
Matt Tester
  • 4,663
  • 4
  • 29
  • 32
manuellt
  • 669
  • 2
  • 7
  • 19

2 Answers2

2
var type = <The type where GetData method is defined>;

var genericType = typeof(w);

var methodInfo = type.GetMethod("GetData");

var genericMethodInfo = methodInfo.MakeGenericMethod(genericType);

//instance or null : if the class where GetData is defined is static, you can put null : else you need an instance of this class.
var data = genericMethodInfo.Invoke(<instance or null>, new[]{w});
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
2

You do not need to write section. C# implicity decides the type of the parameter in a generic method if type is not declared; just go with:

var data = GetData(w);

Here is a sample;

public interface IM
{

}

public class M : IM
{
}

public class N : IM
{

}

public class SomeGenericClass 
{
    public T GetData<T>(T instance) where T : IM
    {
        return instance;
    }
}

And you may call it like;

IM a = new M();
SomeGenericClass s = new SomeGenericClass();
s.GetData(a);
daryal
  • 14,643
  • 4
  • 38
  • 54