Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6370521
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T00:56:26+00:00 2026-05-25T00:56:26+00:00

I’m trying to retrieve MethodInfo for Where method of Enumerable type: typeof (Enumerable).GetMethod(Where, new

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T00:56:27+00:00Added an answer on May 25, 2026 at 12:56 am

    That previous answer works for some cases, however:

    • It doesn’t handle nested generic types, such as a parameter type of Action<IEnumerable<T>>. It will treat all Action<> as matches, for example, string.Concat(IEnumerable<string>) and string.Concat<T>(IEnumerable<T>) will both match if searching for "Concat" with type IEnumerable<> on the string type. What is really desirable is handling nested generic types recursively, while treating all generic parameters as matching each other regardless of name while NOT matching concrete types.
    • It returns the first method matched rather than throwing an exception if the result is ambiguous, like type.GetMethod() does. So, you might get the method you wanted if you’re lucky, or you might not.
    • Sometimes it will be necessary to specify BindingFlags in order to avoid ambiguity, such as when a derived class method ‘hides’ a base class method. You normally want to find base class methods, but not in a specialized case where you know the method you’re looking for is in the derived class. Or, you might know you’re looking for a static vs instance method, public vs private, etc. and don’t want to match if it’s not exact.
    • It doesn’t address another major fault with type.GetMethods(), in that it also doesn’t search base interfaces for methods when looking for a method on an interface type. OK, maybe that’s being picky, but it’s another major flaw in GetMethods() that has been a problem for me.
    • Calling type.GetMethods() is inefficient, type.GetMember(name, MemberTypes.Method, ...) will return only methods with a matching name instead of ALL methods in the type.
    • As a final nit-pick, the name GetGenericMethod() could be misleading, since you might be trying to find a non-generic method that happens to have a type parameter somewhere in a parameter type due to a generic declaring type.

    Here’s a version that addresses all of those things, and can be used as a general-purpose replacement for the flawed GetMethod(). Note that two extension methods are provided, one with BindingFlags and one without (for convenience).

    /// <summary>
    /// Search for a method by name and parameter types.  
    /// Unlike GetMethod(), does 'loose' matching on generic
    /// parameter types, and searches base interfaces.
    /// </summary>
    /// <exception cref="AmbiguousMatchException"/>
    public static MethodInfo GetMethodExt(  this Type thisType, 
                                            string name, 
                                            params Type[] parameterTypes)
    {
        return GetMethodExt(thisType, 
                            name, 
                            BindingFlags.Instance 
                            | BindingFlags.Static 
                            | BindingFlags.Public 
                            | BindingFlags.NonPublic
                            | BindingFlags.FlattenHierarchy, 
                            parameterTypes);
    }
    
    /// <summary>
    /// Search for a method by name, parameter types, and binding flags.  
    /// Unlike GetMethod(), does 'loose' matching on generic
    /// parameter types, and searches base interfaces.
    /// </summary>
    /// <exception cref="AmbiguousMatchException"/>
    public static MethodInfo GetMethodExt(  this Type thisType, 
                                            string name, 
                                            BindingFlags bindingFlags, 
                                            params Type[] parameterTypes)
    {
        MethodInfo matchingMethod = null;
    
        // Check all methods with the specified name, including in base classes
        GetMethodExt(ref matchingMethod, thisType, name, bindingFlags, parameterTypes);
    
        // If we're searching an interface, we have to manually search base interfaces
        if (matchingMethod == null && thisType.IsInterface)
        {
            foreach (Type interfaceType in thisType.GetInterfaces())
                GetMethodExt(ref matchingMethod, 
                             interfaceType, 
                             name, 
                             bindingFlags, 
                             parameterTypes);
        }
    
        return matchingMethod;
    }
    
    private static void GetMethodExt(   ref MethodInfo matchingMethod, 
                                        Type type, 
                                        string name, 
                                        BindingFlags bindingFlags, 
                                        params Type[] parameterTypes)
    {
        // Check all methods with the specified name, including in base classes
        foreach (MethodInfo methodInfo in type.GetMember(name, 
                                                         MemberTypes.Method, 
                                                         bindingFlags))
        {
            // Check that the parameter counts and types match, 
            // with 'loose' matching on generic parameters
            ParameterInfo[] parameterInfos = methodInfo.GetParameters();
            if (parameterInfos.Length == parameterTypes.Length)
            {
                int i = 0;
                for (; i < parameterInfos.Length; ++i)
                {
                    if (!parameterInfos[i].ParameterType
                                          .IsSimilarType(parameterTypes[i]))
                        break;
                }
                if (i == parameterInfos.Length)
                {
                    if (matchingMethod == null)
                        matchingMethod = methodInfo;
                    else
                        throw new AmbiguousMatchException(
                               "More than one matching method found!");
                }
            }
        }
    }
    
    /// <summary>
    /// Special type used to match any generic parameter type in GetMethodExt().
    /// </summary>
    public class T
    { }
    
    /// <summary>
    /// Determines if the two types are either identical, or are both generic 
    /// parameters or generic types with generic parameters in the same
    ///  locations (generic parameters match any other generic paramter,
    /// but NOT concrete types).
    /// </summary>
    private static bool IsSimilarType(this Type thisType, Type type)
    {
        // Ignore any 'ref' types
        if (thisType.IsByRef)
            thisType = thisType.GetElementType();
        if (type.IsByRef)
            type = type.GetElementType();
    
        // Handle array types
        if (thisType.IsArray && type.IsArray)
            return thisType.GetElementType().IsSimilarType(type.GetElementType());
    
        // If the types are identical, or they're both generic parameters 
        // or the special 'T' type, treat as a match
        if (thisType == type || ((thisType.IsGenericParameter || thisType == typeof(T)) 
                             && (type.IsGenericParameter || type == typeof(T))))
            return true;
    
        // Handle any generic arguments
        if (thisType.IsGenericType && type.IsGenericType)
        {
            Type[] thisArguments = thisType.GetGenericArguments();
            Type[] arguments = type.GetGenericArguments();
            if (thisArguments.Length == arguments.Length)
            {
                for (int i = 0; i < thisArguments.Length; ++i)
                {
                    if (!thisArguments[i].IsSimilarType(arguments[i]))
                        return false;
                }
                return true;
            }
        }
    
        return false;
    }
    

    Note that the IsSimilarType(Type) extension method can be made public and might be useful on its own. I know, the name isn’t great – you’re welcome to come up with a better one, but it might get really long to explain what it does. Also, I added yet another improvement by checking for ‘ref’ and array types (refs are ignored for matching, but arrays dimensions must match).

    So, that’s how Microsoft should have done it. It’s really not that hard.

    Yeah, I know, you can shorten some of that logic using Linq, but I’m not a huge fan of Linq in low-level routines like this, and also not unless the Linq is about as easy to follow as the original code, which is often NOT the case, IMO.

    If you love Linq, and you must, you can replace the inner-most part of IsSimilarType() with this (turns 8 lines into 1):

    if (thisArguments.Length == arguments.Length)
        return !thisArguments.Where((t, i) => !t.IsSimilarType(arguments[i])).Any();
    

    One last thing: If you’re looking for a generic method with a generic parameter, such as Method<T>(T, T[]), you’ll have to find a Type which is a generic parameter (IsGenericParameter == true) to pass in for the parameter type (any one will do, because of the ‘wildcard’ matching). However, you can’t just do new Type() – you have to find a real one (or build one with TypeBuilder). To make this easier, I added the public class T declaration, and added logic to IsSimilarType() to check for it and match any generic parameter. If you need a T[], just use T.MakeArrayType(1).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a French site that I want to parse, but am running into
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I need to clean up various Word 'smart' characters in user input, including but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.