HOW CLOSURES WORK

To understand the nature of closures, it’s best to look at some examples that utilize them. Have a look at this code:

static void Closures( ) {

  Console.WriteLine(GetClosureFunction( )(30));

}

 

static Func<int, int> GetClosureFunction( ) {

  int val = 10;

  Func<int, int> internalAdd = x => x + val;

 

  Console.WriteLine(internalAdd(10));

 

  val = 30;

  Console.WriteLine(internalAdd(10));

 

  return internalAdd;

}

Follow the path of execution: the function Closures calls into GetClosureFunction. There is an odd second pair of parentheses behind that call, with the parameter 30. This is because GetClosureFunction returns a function that is then called right away.

In GetClosureFunction, there is a local variable called val, and a local function called internalAdd, which adds val to a parameter called x. internalAdd is then called and the value 10 is passed in. What do you think the output is going to be? The answer is 20 — the value of val plus the parameter 10.

Now val is changed to 30 and internalAdd is called again. The result is 40, so you can learn something here about how the local function works with local variables that live in the same scope: obviously the change to the local variable is picked up by internalAdd, even though it happened after internalAdd had been originally created.

Finally, internalAdd is returned from GetClosureFunction, and as you saw initially, it is being called again with the parameter 30. The result is 60, the last known value ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.