Calling generic method using reflection in .NET [duplicate]
I have a question. Is it possible to call generic method using reflection in .NET? I tried the following code
var service = new ServiceClass();
Type serviceType = service.GetType();
MethodInfo method = serviceType.GetMethod("Method1", new Type[]{});
method.MakeGenericMethod(typeof(SomeClass));
var result = method.Invoke(service, null);
But it throws the following exception "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."
Solution 1:
You're not using the result of MakeGenericMethod
- which doesn't change the method you call it on; it returns another object representing the constructed method. You should have something like:
method = method.MakeGenericMethod(typeof(SomeClass));
var result = method.Invoke(service, null);
(or use a different variable, of course).
Solution 2:
You need to say
method = method.MakeGenericMethod(typeof(SomeClass));
at a minumum and preferably
var constructedMethod = method.MakeGenericMethod(typeof(SomeClass));
constructedMethod.Invoke(service, null);
as instances of MethodInfo
are immutable.
This is the same concept as
string s = "Foo ";
s.Trim();
Console.WriteLine(s.Length);
string t = s.Trim();
Console.WriteLine(t.Length);
causing
4
3
to print on the console.
By the way, your error message
"Late bound operations cannot be performed on types or methods for which
ContainsGenericParameters
istrue
."
if your clue that method
still contains generic parameters.