c# - Lambdas and type inference -


i'm having bit of trouble understanding reason behind why following code giving me error:

 var funs = enumerable.range(0, 10).select(x => (int y) => x + y);  foreach (var fun in funs)    console.writeline("{0}", fun(10)); 

the error "an implicitly typed local variable declaration cannot initialized 'system.collections.generic.ienumerator.current'". know how fix (either specifying type select, such select<int, func<int, int>> or using helper method such private static func<t1, tr> makefunc<t1, tr>(func<t1, tr> f) { return f; } , using select(x => makefunc(y => x + y)).

however, i'd understand reason compiler can't deduce types. best guess far is, according 7.15.6, can't figure out if should translate inner lambda func or expr. correct or there more it?

for reference, here's 7.15.6 says:

"an anonymous function f must converted delegate type d or expression tree type e, either directly or through execution of delegate creation expression new d(f). conversion determines result of anonymous function."

the reason simple:

how can compile conclude should func<int, int>? simple cannot!

suppose had own delegate:

 public delegate int f(int i); 

how compiler choose between func<int, int> , f? these totally different types, 2 things in common: there both delegates , have same signature (one parameter , return type, both of type int).

so compiler cannot choose; have have it:

var funs = enumerable.range(0, 10).select<int, func<int,int>>(x => y => x + y); 

or

var funs = enumerable.range(0, 10).select<int, f>(x => y => x + y); 

one little advantage: can drop int before y.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -