Lambda expression and var keyword in C #

Possible duplicate:
C # Why can't anonymous method be assigned to var?

I have the following instruction in C #

Func <int, int, int> add = (x, y) => x + y; 

But when I replace the left hand operator with the following

 var add = (x, y) => x + y; 

I get a compiler error ( It is not possible to assign a lambda expression to an implicitly typed local variable ). Why?

+26
c # lambda
Aug 01 '11 at 11:16
source share
3 answers

Because the compiler cannot figure out what type of RHS has

 var add = (x, y) => x + y; 

Any type that supports the + operator is a candidate, and since the types x and y are not a restriction of the same type. There were excluded many possible + operators that could be used, and therefore the set of possible types for x and y is quite large, but to determine the type of addition, the compiler should be able to reduce the set to only one type for x and one for y (not quite true , it is possible that both the base class and the derived class will match), and yet, even if the compiler can determine the type for x and y or that you specify types to say int , you will still be left with the fact that both Expression<Func<int,int,int>> and Func<int,int,int> are possible types Pami to add

There are several options for reducing the set of possible types. The compiler may try to see how add will be used later, but not (and perhaps could not determine the types, even if this were done)

+16
Aug 01 '11 at 11:23
source share

The var keyword will not work, because lambda expressions are used for both delegates as expression trees, and the compiler does not know what it needs to convert lambda for. In other words, for (x, y) => x + y lambda: Func<int, int, int> and Expression<Func<int, int, int>> the following types are valid.

+12
Aug 01 2018-11-11T00:
source share

The error you get is that the compiler does not know what types x and y are.

+1
Aug 01 2018-11-11T00:
source share



All Articles