Why does Func / Lambdas allow the return type to overload the method, but the method does not?

I defined these method overloads that differ only in the Action / Func parameter:

public void DoSomethingWithValues(Action<decimal, decimal> d, decimal x, decimal y) { d(x, y); } public void DoSomethingWithValues(Func<decimal, decimal, decimal> d, decimal x, decimal y) { var value = d(x, y); } 

I try to call them through the built-in lambda, Func <> and method:

  public Func<decimal, decimal, decimal> ImAFuncWhichDoesSomething = (x, y) => (x + y) / 5; public decimal ImAMethodWhichDoesSomething(decimal x, decimal y) { return (x + y + 17) / 12; } public void DoSomething() { DoSomethingWithValues((x, y) => (x - y) / 17 , 1, 2); // Inline lambda compiles OK DoSomethingWithValues(ImAFuncWhichDoesSomething, 1, 2); // Func<> compiles OK DoSomethingWithValues(ImAMethodWhichDoesSomething, 1, 2); // Method generates "ambiguous invocation" error!! } 

The first two are compiled and resolved by the return type.

However, the method does not compile due to an "ambiguous call" error!

Why does lambda / func allow overloading by return type and the method does not work?

+6
source share

Source: https://habr.com/ru/post/979833/


All Articles