Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Surrounding a lambda expression parameter with parentheses

I've been following this tutorial today to learn a bit about the Web API and noticed something - in the tutorial code, there was this line:

var product = products.FirstOrDefault((p) => p.Id == id);

As you can see the parameter "p" is provided in parentheses. Since it's not mandatory having it this way, I'm curious if there's any benefit to doing it that way or if it's just a preference of the developer?

like image 964
EvilBeer Avatar asked Sep 16 '26 18:09

EvilBeer


2 Answers

In this case, it's purely developer preference.

Parenthesises are needed when you have more than one parameter. For example:

var singleString = someStrings.Aggregate((current, next) => current + Environment.NewLine + next);
like image 188
nvoigt Avatar answered Sep 19 '26 17:09

nvoigt


The C# specification explicitly states that (p) => ... can be written as p => ...:

7.15 Anonymous function expressions

...

In an anonymous function with a single, implicitly typed parameter, the parentheses may be omitted from the parameter list. In other words, an anonymous function of the form

( param ) => expr

can be abbreviated to

param => expr

So there is no technical difference whatsoever, only personal preference.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!