_ => what does this mean in lambda expressions?

What does a lambda expression mean, for example _=> expr ?

What is the purpose of _ as an entrance to lambda?

Example:

 int sum = 0; list.ForEach(_=> { sum += 1; }); 
+78
c # lambda
May 6 '10 at 4:02 a.m.
source share
5 answers

This convention is used when you do not need a parameter.

+59
May 6 '10 at 4:04
source share

This parameter name, although not useful, is usually used (by some conventions) when you need to indicate that the expression has a parameter in order to get the code to compile, but you don’t know, I really care about it, so you just ignore it him.

It mainly uses syntax for what is a legal identifier in C #, and since the identifier can begin with an underscore and not contain anything else, it's just the name of the parameter.

You could just write:

 var _ = 10; 
+35
May 6 '10 at 4:07
source share

_ is a valid variable name. They just use _ as a variable.

+22
May 6 '10 at 4:05
source share

Since the lamda expression is mainly used in short anonymous code, so the variable name is sometimes not necessary, even they do not use the variable in the code block, so they just give _ for short, convention

+9
May 6 '10 at 4:13
source share

I also use _ => _.method() for a single-line, lambdas invocation method, as it reduces the cognitive weight of the command. Especially when using generics, writing x => x.method() simply adds that the split second consideration is "What is 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 character. This avoids redundancy by determining that the type of the argument is obvious and can be taken out of use - just like using "var" to prevent the type declaration from repeating. Writing client=>client.Init() here will simply make the instruction longer without adding any meaning to it.

Obviously, this does not apply to parameters that must be passed to a method, which should be called descriptively. For example: Do( id=>Log(id) );

Using a unidirectional parameter for method calls is hardly justified when using a block of code instead of a single-line one, since the lambda identifier is disconnected from the definition of its generics. In general, when the same identifier is to be reused, give it a descriptive name.

The bottom line is that verbosity is justified only for values, especially for lambda, which were created to simplify the creation of anonymous delegates. In any case, common sense should be used, balancing clarity and brevity. If a character is just a “hook” for real functionality, then a single character identifier works fine. This is the case with For-loops and the letters "i" and "j" as indexers.

+3
Jan 23 '17 at 13:19
source share



All Articles