I’m new in C# and earlier I saw the lambda expression is like
(params) => { expression; }
but in LINQ, I saw examples like
IEnumerable<string> customerFirstNames = customers.Select(cust => cust.FirstName);
No brackets.
(I actually mean both {} and () – regardless if we call them braces, parenthesis, or brackets.)
Are they the same or is there any difference?
Thanks a lot.
The rules are:
A lambda expression has the form
Let’s consider the left side first.
The modifier can be ref, out or nothing at all.
If there are no ref or out modifiers then all the types can be elided. If there are any ref or out modifiers then every parameter declaration must have a declared type. If any paramter has a declared type then every parameter must have a declared type. So you can elide the types provided that (1) there are no refs or outs, and (2) you elide all of them. Otherwise, you must provide all the types.
If there is exactly one parameter and its type has been elided then the parentheses around the parameter list may optionally be elided also.
That’s all the rules about parameter lists. The rules about the right side are:
if the statement list consists of a single return statement with an expression:
then the braces, return keyword and semicolon may be elided:
furthermore, if the statement list consists of a single statement that is a statement expression:
then it is also legal to elide the braces and semicolon:
Note that these now potentially mean something different to the reader! Before we were clearly discarding the return values; now the lambdas will be read as returning them.
Note that this means it is legal to do this trick with void returning methods. This is actually legal:
Yuck. Don’t do that. If you mean
then say that instead. The former looks too much like you are trying to say
which of course would be illegal.