0

I read through this explanation of lambdas by @mk. and it has the following example:

Func<int, Func<int, int>> adder = 
    (int x) => (int y) => x + y; // `int` declarations optional
Func<int, int> add5 = adder(5);
var add6 = adder(6); // Using implicit typing
Debug.Assert(add5(1) == 6);
Debug.Assert(add6(-1) == 5);

// Closure example
int yEnclosed = 1;
Func<int, int> addWithClosure = 
    (x) => x + yEnclosed;
Debug.Assert(addWithClosure(2) == 3);

I've used lambdas in C# for years and yet I do not understand what is going on here. Obviously this adds an instance variable, but what in the declaration is defining all this? Is x or y the instance variable? And what's with the Closure example at the bottom?

David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • 1
    Its a delegate that returns a delegate, right? –  Jun 13 '21 at 19:48
  • [How to use closures in C#](https://www.infoworld.com/article/3620248/how-to-use-closures-in-csharp.html) –  Jun 13 '21 at 20:14

0 Answers0