Short version :
We can get the typeof Func<T,T>
using:
typeof(Func<,>)
but what if I want to get the type of Func<T, bool>
, what should I use, or is it possible to do? Clearly this doesn't compile :
typeof(Func<, bool>)
Long version :
Consider the following scenario, I have two similar method and I want to get the second one (Func<T, int>
) using Reflection:
public void Foo<T>(Func<T, bool> func) { }
public void Foo<T>(Func<T, int> func) { }
I'm trying this:
var methodFoo = typeof (Program)
.GetMethods()
.FirstOrDefault(m => m.Name == "Foo" &&
m.GetParameters()[0]
.ParameterType
.GetGenericTypeDefinition() == typeof (Func<,>));
But since the generic type definition of Func<T, bool>
and Func<T, int>
are equal it gives me the first method. To fix this I can do the following:
var methodFoo = typeof (Program)
.GetMethods()
.FirstOrDefault(m => m.Name == "Foo" &&
m.GetParameters()[0]
.ParameterType
.GetGenericArguments()[1] == typeof(int));
Then I get the correct method but I do not like this way. And it seems like a overhead for more complex situations. What I want to do is get the type of Func<T,bool>
like in my failed attempt above, then instead of using Linq I can use this overload of GetMethod
and do something like the following:
var methodFoo = typeof (Program)
.GetMethod("Foo",
BindingFlags.Public | BindingFlags.Instance,
null,
new[] {typeof (Func<, bool>)}, // ERROR typeof(Func<,>) doesn't work either
null);
Note: Ofcourse Func<T,T>
is just an example, question is not specific to any type.