Search code examples
c#lambdareflectionexpression

How can I get the MethodInfo of Expression.Lambda<TDelegate>(Expression, ParameterExpression[])?


I'm trying to get the MethodInfo of the static Expression.Lambda<TDelegate>(Expression, ParameterExpression[]) method. But I'm getting an AmbiguousMatchException when I try with GetMetod:

MethodInfo lambda = typeof(Expression).GetMethod(nameof(Expression.Lambda), new[] { typeof(Expression), typeof(ParameterExpression[]) });

I have figured out a very convoluted way by getting all public static methods and filtering:

MethodInfo lambda = (
    from m in typeof(Expression).GetMethods(BindingFlags.Public | BindingFlags.Static)
    let p = ((MethodBase)m.ReturnParameter.Member).GetParameters()
    where m.Name == nameof(Expression.Lambda) && m.ReturnType.IsGenericType 
                                              && p.Length == 2 
                                              && p[0].ParameterType == typeof(Expression) 
                                              && p[1].ParameterType == typeof(ParameterExpression[])
    select m
).Single();

It works but seems overly complicated and pretty dangerous (cast to MethodBase plus Single() call).

Is there a simpler solution to get that generic MethodInfo?


Solution

  • Just add the number of type parameters to the GetMethod call, this will uniquely identify a generic method (because you can't have two methods with the same number of generic type parameters, but you can have with a different number).

    var method = typeof(Expression)
        .GetMethod(
          nameof(Expression.Lambda),
          1,
          new[] { typeof(Expression), typeof(ParameterExpression[]) }
        );
    

    dotnetfiddle.net