📜 ⬆️ ⬇️

Lambda

Some time ago I learned about lambdas, but did not quite understand the principles of constructing expressions with lambdas. But today I came across the post of Charlie Calvert and clarified everything for myself.

Consider an example:
Func< int , int , int > myLambda = (a, b) => (a + b);

* This source code was highlighted with Source Code Highlighter .

This entry is equivalent to the following code block:
public static int Add( int a, int b)
{
return a + b;
}

Func< int , int , int > myDelegate = Add;


* This source code was highlighted with Source Code Highlighter .

You may notice that the left sides of the expression are identical:
Func< int , int , int > myLambda = (a, b) => (a + b);
Func< int , int , int > myDelegate = Add;

* This source code was highlighted with Source Code Highlighter .

Well, now, if you take a close look at the right-hand side, you can notice one feature.
Compare the right parts of the expressions: (a, b) and Add. In brackets we have the arguments of the Add method, and (a + b) is the body of the Add method.
That is, if it is simple, what goes in the right part before the lambda "=>" are the arguments of the method, and that after the lambda is the body of the method.

You can also submit a method with no arguments:
public static void UseLocal()
{
int n;
Func< int > func = () => { n = 6; return n; };
n = func();
Console .WriteLine(n); // Outputs the number 6
}

* This source code was highlighted with Source Code Highlighter .


Well, for those who, perhaps, do not know how all this is pronounced: (a, b) => a + b read “a and b go into a plus b”.
')
After this enlightenment, everything became clear to me, and I hope that I will not look at examples when creating lambda expressions anymore :)

And here is the source: blogs.msdn.com/charlie/archive/2008/06/28/lambdas.aspx

UPD: here you can read about the circuit, and the problems that arise

Source: https://habr.com/ru/post/51565/


All Articles