Reading through C# in a Nutshell I noticed this bit of code that I've never came across:
_uiSyncContent.Post(_ => txtMessage.Text += "Test");
What is that underscore followed by an arrow? I've seen Lambda expressions written in a similar way but nothing with an underscore.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
The underscore symbol _ is a valid identifier in JavaScript, and in your example, it is being used as a function parameter. A single underscore is a convention used by some javascript programmers to indicate to other programmers that they should "ignore this binding/parameter".
With the minor difference that _ would be accessible as an argument within the arrow function (although it will likely have the value undefined ), whereas the second snippet won't have any accessible arguments.
() says that the function does not expect any arguments, it doesn't declare any parameters. The function's . length is 0. If you use _ , it explicitly states that the function will be passed one argument, but that you don't care about it. The function's .
It's just a lambda expression that uses _
instead of x
for its parameter. _
is a valid identifier so it can be used as a parameter name.
As mentioned in the comments, it's a convention among some developers to call it _
to indicate that it's not actually used by the lambda expression, but it's no more than that: a convention.
Note that this is not the same thing as a discard (introduced several years after this answer), which is a special variable for assigning values that aren't going to be used and will instead be discarded. Unlike discarded values, _
parameters continue to exist in lambda scope; they just aren't used anywhere in the lambda expression. And there can only be one _
in scope at a time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With