Calling generic method using reflection in .NET
.NetGenericsReflection.Net Problem Overview
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."
.Net Solutions
Solution 1 - .Net
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 - .Net
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
is true
."
if your clue that method
still contains generic parameters.