Possible Duplicate:
C# Why can't an anonymous method be assigned to var?
I have following statement in c#
Func <int, int, int> add = (x, y) => x + y;
But when I am replacing left hand side statement with following
var add = (x, y) => x + y;
I am getting compiler error(Cannot assign lambda expression to an implicitly-typed local variable).Why?
Because the compiler can’t figure out what type the RHS has from
Any type that supports the
+operator is a candidate and since the type of x and y is not constraint to be of the same type. There’s quite a lot of possible+operators that could be used and therefore the set of possible types for x and y is rather large but to be able to determine the type of add, the compiler need to be able to reduce the set to just one type for x and one for y (not exactly true, it might be that both a base class and a derived class would fit) and still even if the compiler could figure out the type for x and y or that you specified the types to let’s sayintyou’d still be left with the fact that bothExpression<Func<int,int,int>>andFunc<int,int,int>are possible types for addThere are multiple options for how to reduce the set of possible types. The compiler could try to look at how
addis used later but doesn’t (and potentially couldn’t figure the types out even if it did)