views:

55

answers:

1

I'm trying to retrieve MethodInfo for Where method of Enumerable type:

typeof (Enumerable).GetMethod("Where", new Type[] { typeof(IEnumerable<>), typeof(Func<,>) })

but get null. What am I doing wrong?

+4  A: 

Unfortunately, generics are not well-supported in .NET Reflection. In this particular case, you'll need to call GetMethods and then filter the result set for the method you're looking for. An extension method like the following should do the trick.

public static class TypeExtensions
{
    private class SimpleTypeComparer : IEqualityComparer<Type>
    {
        public bool Equals(Type x, Type y)
        {
            return x.Assembly == y.Assembly &&
                x.Namespace == y.Namespace &&
                x.Name == y.Name;
        }

        public int GetHashCode(Type obj)
        {
            throw new NotImplementedException();
        }
    }

    public static MethodInfo GetGenericMethod(this Type type, string name, Type[] parameterTypes)
    {
        var methods = type.GetMethods();
        foreach (var method in methods.Where(m => m.Name == name))
        {
            var methodParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray();

            if (methodParameterTypes.SequenceEqual(parameterTypes, new SimpleTypeComparer()))
            {
                return method;
            }
        }

        return null;
    }
}

With this in hand the following code will work:

typeof(Enumerable).GetGenericMethod("Where", new Type[] { typeof(IEnumerable<>), typeof(Func<,>) });
Dustin Campbell