.net - Why doesn't the C# compiler automatically infer the types in this code? -
why c# compiler not infer fact fooext.multiply()
satisfies signature of functions.apply()
? have specify separate delegate variable of type func<foo,int,int>
code work ... seems type inference should handle this. wrong? and, if so, why?
edit: compilation error received is:
the type arguments method
firstclassfunctions.functions.apply<t1,t2,tr>(t1, system.func<t1,t2,tr>, t2)'
cannot inferred usage. try specifying type arguments explicitly
namespace firstclassfunctions { public class foo { public int value { get; set; } public int multiply(int j) { return value*j; } } public static class fooext { public static int multiply(foo foo, int j) { return foo.multiply(j); } } public static class functions { public static func<tr> apply<t1,t2,tr>( t1 obj, func<t1,t2,tr> f, t2 val ) { return () => f(obj, val); } } public class main { public static void run() { var x = new foo {value = 10}; // line below won't compile ... var result = x.apply(fooext.multiply, 5); // will: func<foo, int, int> f = fooext.multiply; var result = x.apply(f, 5); } }
i believe result of vs2008 c# compiler's inability correctly infer types involved when converting method group delegate. @eric lippert discusses behavior in post c# 3.0 return type inference not work on method groups.
if recall correctly, improvements made in new c# compiler that's part of vs2010 expands cases method group inference possible.
now, rules type inference quite complicated, , i'm far expert in subject. real knowledge can address question if mistaken.
Comments
Post a Comment