What are the rules the C# compiler uses to resolve types in a lambda expression? -


with reference why can't anonymous method assigned var?, understand following not supported in c#:

var func = (x,y) => math.log(x) + math.log(y); 

however, can create method, func of form:

public static func<t,t,t> func<t>(func<t,t,t> f) => f; 

and do:

var func = func<double>((x,y) => math.log(x) + math.log(y)); 

that compile fine. however, lambdas different types parameters , return value, things odd. example, if have method:

public static func<t1,t2,t3> func<t1,t2,t3>(func<t1,t2,t3> f) => f; 

i can example do:

var func = func((double x, double y) => $"{x + y}"); 

and compile. c# compiler seems able infer return type lambda. but, following won't compile:

var func = func((x,y) => math.log(x) + math.log(y)); 

as compiler doesn't seem able infer types of x , y way used in body.

so, question: definitive rules on type inference of lambda expressions; compiler infer , won't it?

what definitive rules on type inference of lambda expressions;

the definitive rules in specification. if want @ implementation, can find enough in roslyn sources; commented pretty heavily, anticipating there questions. note in particular comment starting around line 110 relevant question; study if want deep understanding of how lambda type inference works.

https://github.com/dotnet/roslyn/blob/master/src/compilers/csharp/portable/binder/semantics/overloadresolution/methodtypeinference.cs

consider compiling compiler in debug mode; can use dump method @ breakpoints describe state of type inference engine goes. used facilitate more rapid debugging, , when considering extensions algorithm. (some of still in code, commented out.)

what compiler infer , won't it?

that far broad question answer definitively. basic action respect examples in question is:

  • bounds on type parameters inferred ordinary arguments matched formal parameter types.
  • lambdas formal parameter types of lambda inferred or known have return types inferred
  • the previous step repeated until algorithm fails make progress or deduces contradiction.

i recorded video -- ten years ago -- explaining step step apparently no longer on msdn. vexed.