Sven-Michael Stübe
Sven-Michael Stübe

Reputation: 14750

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?

Upvotes: 25

Views: 5916

Answers (4)

Arad
Arad

Reputation: 12764

Now You Can!

From C# 9.0 onwards, you can use the underscore character to "discard" one or more lambda parameters. From Microsoft Docs:

Beginning with C# 9.0, you can use discards to specify two or more input parameters of a lambda expression that aren't used in the expression:

Func<int, int, int> constant = (_, _) => 42;

Upvotes: 5

Anders Abel
Anders Abel

Reputation: 69260

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 _.)

Upvotes: 21

John Demetriou
John Demetriou

Reputation: 4381

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

Upvotes: 1

Nick Butler
Nick Butler

Reputation: 24383

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.

Upvotes: 9

Related Questions