Unfortunately, in order to get the generic generic methods using Type.GetMethod(string name, Type[] types)
you have to provide the method the right generic types in the Type[]
, which means that when you try to do this:
Type requiredType = typeof(IEnumerable<>);
typeof(Enumerable).GetMethod("SequenceEqual", new Type[] { requiredType, requiredType });
You actually needed to do something like that:
Type requiredType = typeof(IEnumerable<TSource>);
typeof(Enumerable).GetMethod("SequenceEqual", new Type[] { requiredType, requiredType });
Since if you look at the signature of SequenceEqual
, the generic type is IEnumerable<TSource>
not IEnumerable<>
.
public static IEnumerable<TSource> SequenceEqual<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);
BUT: you don't have access to the type TSource
in order use it.
So the only way to get IEnumerable<TSource>
is using reflection like the following:
MethodInfo info = typeof(Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(x => x.Name.Contains("SequenceEqual"))
.Single(x => x.GetParameters().Length == 2);
Type genericType = typeof(IEnumerable<>).MakeGenericType(infos.GetGenericArguments());
and than getting the method using
typeof(Enumerable).GetMethod("SequenceEqual", new Type[] { genericType, genericType });
But this requires us to get the SequenceEqual
method anyway, so the sad fact is getting the method a generic method when there are few overloads using GetMethod
instead of GetMethods
is practically impossible* (You CAN implement a Binder
and use it in the GetMethod
method but it will require very long coding which will possibly be buggy and unmaintainable and should be avoided).