With reference to Why can't an anonymous method be assigned to var?, I understand that the following is not supported in C#:
var func = (x,y) => Math.Log(x) + Math.Log(y);
However, I can create a method, Func
of the form:
public static Func<T,T,T> Func<T>(Func<T,T,T> f) => f;
and then do:
var func = Func<double>((x,y) => Math.Log(x) + Math.Log(y));
that will compile just fine. However, for lambdas with different types for the parameters and return value, things get odd. For example, if I have a method:
public static Func<T1,T2,T3> Func<T1,T2,T3>(Func<T1,T2,T3> f) => f;
I can for example do:
var func = Func((double x, double y) => $"{x + y}");
and that too will compile. So the C# compiler seems to be able to infer the return type for a lambda. But, the following won't compile:
var func = Func((x,y) => Math.Log(x) + Math.Log(y));
as the compiler doesn't seem able to infer the types of x
and y
from the way they are used in the body.
So, my question: what are the definitive rules on type inference of lambda expressions; what will the compiler infer and what won't it?