lambda expression and var keyword in c# [duplicate

2019-02-07 18:37发布

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?

标签: c# lambda
3条回答
劫难
2楼-- · 2019-02-07 19:12

Because the compiler can't figure out what type the RHS has from

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

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 quit 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 say int you'd still be left with the fact that both Expression<Func<int,int,int>> and Func<int,int,int> are possible types for add

There are multiple options for how to reduce the set of possible types. The compiler could try to look at how add is used later but doesn't (and potentially couldn't figure the types out even if it did)

查看更多
三岁会撩人
3楼-- · 2019-02-07 19:25

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

查看更多
SAY GOODBYE
4楼-- · 2019-02-07 19:34

The error you are getting is because the compiler does not know what type x and y are.

查看更多
登录 后发表回答