Friday, May 16, 2014

What does the _ in lambda expressions stand for?

While reading this interesting blog post by Stephen Cleary, I noticed that he used the following lambda construct in some of the code:

_ => action()

At first, I couldn't figure out what it meant, but like so many times before, Google search came to the rescue (here and here).

It turns out that this is a C# idiom. Since _ (underscore) is a valid C# identifier, it is applied here to represent an ignored identifier in a single-input-parameter lambda expression. It is the same as writing for example:

x => action()


(x) => action()

but it is thought to be more obvious that the parameter on the left-hand-side of the lambda expression will be ignored if an underscore identifier is used.

Now, the accepted answer on StackOverflow and the associated blog post is a little careless with the wording: this idiom is actually not applicable to parameter-less lambdas, i.e. the empty parentheses () in

() => action()

cannot be replaced with _. This would imply a mismatch between the number of input parameters in the () lambda expression (0), and _ (1). Trying to use _ with parameter-less lambdas will inevitably lead to compilation errors.

No comments:

Post a Comment