C# lambda unnamed parameters

is it possible, to discard some arguments in lambda expressions by don't give them a name? E.g. I have to pass a Action<int,int>, but I'm only interested in the second param, i want to write something like

(_, foo) => bar(foo)
// or
(, foo) => bar(foo)

In the first case it is working. But the first parameter isn't really unnamed, because it has the name "_". So it isn't working, when I want to discard two or more. I choose _ because in prolog it has the meaning "any value".

So. Is there any special character or expression for my use case?

Answers


No, you can't. Looking at the C# language specification grammar, there are two ways to declare lambdas: explicit and implicit. Neither one allows you to skip the identifier of the parameter or to reuse identifiers (names).

explicit-anonymous-function-parameter:
  anonymous-function-parameter-modifieropt   type   identifier

implicit-anonymous-function-parameter:
  identifier

It's the same as for unused function parameters in ordinary functions. They have to be given a name.

Of course you can use _ as the name for one of the parameters, as it is a valid C# name, but it doesn't mean anything special.

As of C# 7, _ does have a special meaning. Not for lambda expression parameter names but definitely for other things, such as pattern matching, deconstruction, out variables and even regular assignments. (For example, you can use _ = 5; without declaring _.)


The short answer is: no, you have to name every parameter, and the names have to be unique.

You can use _ as one parameter name because it is a valid identifier in C#. However, you can only use it once.


In C# 7, you can use discards. Discards are write only variables which you can not read. It is basically for variables that you do not wish to use more details here


Need Your Help

Optional parameters with named query in Hibernate?

java hibernate orm hql named-query

Is there any way to specify optional parameters (such as when search parameters are provided from a form and not all parameters are required) in a named query when using Hibernate? I'm using a nati...

How to reset EditText after an action has been completed?

android reset android-edittext revert

I would like to reset my EditText back to an empty "space" or a "hint" after a button has pressed that would have completed an activity with input from the EditText field.