In my quest to understand the very odd looking \' => \' operator, I have found a good place to start, and the author is very concise and clear:
Well, you can see a lambda as a quick way to write a method that you only want to use once. For instance, the following method
private int sum5(int n)
{
return n + 5;
}
is equivalent to the lambda: (n) => n + 5
. Except that you can call the method anywhere in your class, and the lambda lives only in the scope it is declared (You can also store lambdas in Action and Func objects)
Other thing that lambdas can do for you is capturing scope, building a closure. For example, if you have something like this:
...methodbody
int acc = 5;
Func addAcc = (n) => n + acc;
What you have there is a function that accepts an argument as before, but the amount added is taken from the value of the variable. The lambda can live even after the scope in which acc was defined is finished.
You can build very neat things with lambdas, but you have to be careful, because sometimes you lose readability with tricks like this.