c# - How do I use reflection to call a generic method? -
what's best way call generic method when type parameter isn't known @ compile time, instead obtained dynamically @ runtime?
consider following sample code - inside example()
method, what's concise way invoke genericmethod<t>()
using type
stored in mytype
variable?
public class sample { public void example(string typename) { type mytype = findtype(typename); // goes here call genericmethod<t>()? genericmethod<mytype>(); // doesn't work // changes call staticmethod<t>()? sample.staticmethod<mytype>(); // doesn't work } public void genericmethod<t>() { // ... } public static void staticmethod<t>() { //... } }
you need use reflection method start with, "construct" supplying type arguments makegenericmethod:
methodinfo method = typeof(sample).getmethod("genericmethod"); methodinfo generic = method.makegenericmethod(mytype); generic.invoke(this, null);
for static method, pass null
first argument invoke
. that's nothing generic methods - it's normal reflection.
as noted, lot of simpler of c# 4 using dynamic
- if can use type inference, of course. doesn't in cases type inference isn't available, such exact example in question.