Difference between expression lambda and statement

2020-05-18 11:34发布

Is there a difference between expression lambda and statement lambda?

If so, what is the difference?

Found this question in the below link but could not understand the answer What is Expression Lambda?

C# interview Questions

The answer mentioned in that link is this A lambda expression with an expression on the right side is called an expression lambda.

Per my understanding always the expression is in the right hand side only. That is why I am asking this question. Is there anything I am unaware of?

4条回答
迷人小祖宗
2楼-- · 2020-05-18 11:35

lampda expression is an anonymous function that the compiler can either turn into a Func<T> or an Expression<Func<T>> (inferred by compiler depending on usage).

It is not entirely clear what you mean by "expression lamdba", but if you have heard the phrase in a podcast/webcast or something it is probably either referring to a lambda expression. Or it could be the property Expression.Lambda, which you use to obtain a lambda from an Expression instance.

查看更多
该账号已被封号
3楼-- · 2020-05-18 11:41

Yes there is - or I should probably say that one defines the other.

A lambda expression allows you to assign simple anonymous functions.

An expression lambda is a type of lambda that has an expression to the right of the lambda operator.

The other type of lambda expression is a statement lambda because it contains a statement block {...} to the right side of the expression.

  • Expression lambda takes the form: number => (number % 2 == 0)
  • Statement lambda takes the form: number => { return number > 5 }
查看更多
你好瞎i
4楼-- · 2020-05-18 11:51

This is indeed confusing jargon; we couldn't come up with anything better.

A lambda expression is the catch-all term for any of these:

x => M(x)
(x, y) => M(x, y)
(int x, int y) => M(x, y)
x => { return M(x); }
(x, y) => { return M(x, y); }
(int x, int y) => { return M(x, y); }

The first three are expression lambdas because the right hand side of the lambda operator is an expression. The last three are statement lambdas because the right hand side of the lambda operator is a block.

This also illustrates that there are three possible syntaxes for the left side: either a single parameter name, or a parenthesized list of untyped parameters, or a parenthesized list of typed parameters.

查看更多
虎瘦雄心在
5楼-- · 2020-05-18 11:51

A lambda expression is a syntax that allows you to create a function without name directly inside your code, as an expression.

There are two kinds of lambda expressions, depending on their body:

  • expression lambdas, whose body is just an expression, e.g. (i, j) => i + j
  • statement lambdas, whose body is a full statement, e.g.. (i, j) => { return i + j; }
查看更多
登录 后发表回答