Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to get the MethodInfo from a method TableExists<T> so I can call it with a type.

The method is declared inside OrmLiteSchemaApi class. There are 2 overloads:

public static bool TableExists<T>(this IDbConnection dbConn)
  // code omitted
public static bool TableExists(this IDbConnection dbConn, string tableName, string schema = null)
  // code omitted

I am trying to get the MethodInfo like this:

var tableMethod = typeof(OrmLiteSchemaApi).GetMethod("TableExists");

But it generates exception:

System.Reflection.AmbiguousMatchException: 'Ambiguous match found.'

I could only find an old question related to this that suggested to pass an empty object array as parameter but this doesn't seem to work for .net core.

I guess I need to specify the specific overload but I am not sure exactly how.

How do I get the MethodInfo?

To be clear, you're trying to get the first overload? You'll need to pass the parameter type for that (the fact that it's an extension method doesn't change the fact that the first parameter is of type IDbConnection). – Joe Sewell May 10, 2019 at 18:32

You can use GetMethods (plural!) to get an array of all matching methods, and then look for the one which has IsGenericMethod:

var tm = typeof(OrmLiteSchemaApi)
        .GetMethods()
        .Where(x => x.Name == "TableExists")
        .FirstOrDefault(x => x.IsGenericMethod);

I recommend this over using parameter specifiers, since it'll give you an object you can step through at debug time if there are ever any problems.

Passing an empty object array would only work if you're looking for a function with no parameters. Instead, you need to use a different overload of GetMethod that specifies the types of parameters as a type array. That way you can tell it which reference to get by specifying which types of parameters it should look for.

GetMethod(string) will return a method with parameters. The exception isn't thrown because the method has parameters, but because there are two methods with that name. But the solution is still the same. – Scott Hannen May 10, 2019 at 18:36 @ScottHannen, correct. I was referring to the OP's attempted solution to pass an empty object array. That would not return the correct value, since the method being searched for has a parameter. – Louis Ingenthron May 10, 2019 at 18:38

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.