Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_=> what does this underscore mean in Lambda expressions?

Tags:

c#

lambda

c#-4.0

That is a convention used when you don't care about the parameter.


It is a parameter name, albeit not a useful one, but it's the one typically used (by some conventions) when you need to specify that the expression has a parameter in order to get the code to compile, but you don't really care about it, so you're just going to ignore it.

It's basically exploiting the syntax for what a legal identifier in C# constitutes, and since an identifier can start with an underscore, and contain nothing else, it's just a parameter name.

You could just have easily have written:

var _ = 10;

_ is a valid variable name. They are just using _ as a variable.


Because lamda expression is mostly used in a short, anonymous code so that the name of the variable sometimes is not neccessary, even they do not use the variable in the code block, so that they just give a _ for a short, convention


I also second the use of _ => _.method() for one-line, method-call lambdas, since it reduces the instruction's cognitive weight. Specially when using generics, writing x => x.method() just adds that split-second consideration of "What's this 'x'? Is it a coordinate in space?".

Consider the following case:

Initialize<Client> ( _=>_.Init() );

Used with a Generics call, the underscore in this case works as a "bypass symbol". It avoids redundancy, defining that the type of the argument is obvious and can be infered from usage - just as when you use 'var' to prevent repeating a type declaration. Writing client=>client.Init() here would just make the instruction longer without adding any meaning to it.

Obviously, this doesn't apply to the parameters to be passed to the method, which should be named descriptively. Eg.: Do( id=>Log(id) );

The single-underscore-parameter usage for method calls is hardly justifiable when using a block of code instead of a one-liner, since the lambda identifier gets disconnected from its generics definition. In general when the same identifier is to be reused, give it a descriptive name.

The bottom line is that verbosity is only justifiable for disambiguation, especially for lambdas, which were created to simplify anonymous delegates creation in the first place. In any case, common sense should be used, balancing out legibility and conciseness. If the symbol is only a "hook" to the real functionality, one character identifiers are perfectly fine. That's the case with For-loops and the "i" and "j" letters as indexers.