views:

6083

answers:

2

What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?

Consider the following sample code - inside the Example() method, what's the most concise way to invoke GenericMethod() using the type stored in the myType variable?

public class Sample
{

    public void Example(string typeName)
    {
        Type myType = FindType(typeName);

        // what goes here to call GenericMethod<T>() ?    
        GenericMethod<myType>(); // This doesn't work

        // what changes to call StaticMethod<T>() ?
        Sample.StaticMethod<myType>(); // This also doesn't work
    }

    public void GenericMethod<T>()
    {   
        ...
    }

    public static void StaticMethod<T>()
    {   
        ...
    }    
}
+3  A: 

This is the same as a question I asked the other week: http://stackoverflow.com/questions/196936/reflection-and-generic-types

I then covered how to call a generic overloaded method on my blog: http://www.aaron-powell.com/blog.aspx?id=1257

Slace
+31  A: 

You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod:

MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
Jon Skeet