11

Possible Duplicate:
What are ‘closures’ in .NET?

I am currently looking at lambda expression and the word closure keeps coming. Can someone explain it to me in real simple language.

Community
  • 1
  • 1
Sandbox
  • 7,910
  • 11
  • 53
  • 67
  • 20
    If you've got a smart 5 year old, then "A closure is a first-class function with free variables that are bound in the lexical environment." – Dominic Rodger Nov 09 '09 at 11:47
  • 13
    Uhm, you don't? Let your kid play with other kids instead... (note: Silly title gives silly answers...) – Lasse V. Karlsen Nov 09 '09 at 11:51
  • 4
    If you have the mental capacity of a 5-year old, chances are high that you will not understand closures. – JesperE Nov 09 '09 at 12:10
  • 2
    If you have the mental capacity of a 5-year old, chances are high that you won't understand any of these answers too. – Dominic Rodger Nov 09 '09 at 12:14
  • A similar question, which however motivates the "6 year old" part; notice the completely different result! http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Blaisorblade Jan 19 '12 at 18:42
  • 2
    If you've got a really smart 5 year old, then "you'll never get laid if you keep asking those questions". Problem solved. – Jorge Córdoba Apr 05 '13 at 15:07

9 Answers9

20

I'd say this is a duplicate of: What are ‘closures’ in .NET?

"In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created - i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing."

Community
  • 1
  • 1
Jorge Córdoba
  • 51,063
  • 11
  • 80
  • 130
12

Your shoes are in the hall; your jacket is in the kitchen. Put them on, and your gloves (they're in the drawer), when going outside.

Now you can go playing with your cars. At eleven o'clock you must go buy some bread in the corner store.

Kid plays. Forgets all the world.

Alarm clock goes off; kid sees: eleven o'clock! Oh - go outside to buy bread using the "going outside" closure.

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • 1
    Most children learn to tell the time a bit later than 5. They're just busy learning numerals 1-10 aged 5. Just sayin'. ;-) – Dominic Rodger Nov 09 '09 at 12:12
  • They'll listen to the buzzer. But this is about _programming_ children, they do basic math at 5 (though they can't put on their shoes by themselves...) – xtofl Nov 09 '09 at 12:14
  • 1
    mine actually keep cleaning their closure cache... :( – xtofl Nov 09 '09 at 12:15
  • so the kid gets to the store at 11pm and finds the store has suffered a closure and is no longer open? i thought that's where we were going here... – Simon_Weaver May 04 '11 at 06:18
11

I like the Google example for Javascript (you can morph it for C# easily). It's not something a 5 year old would understand but then I doubt an average 5 year old would understand what a function was.

/*
* When a function is defined in another function and it
*    has access to the outer function's context even after
*    the outer function returns
* An important concept to learn in Javascript
*/

function outerFunction(someNum) {
  var someString = 'Hai!';
  var content = document.getElementById('content');
  function innerFunction() {
    content.innerHTML = someNum + ': ' + someString;
    content = null; // IE memory leak for DOM reference
  }
  innerFunction();
}
Chris S
  • 64,770
  • 52
  • 221
  • 239
  • 3
    innerFunction however is not available after outerFunction returns; what's shown there is possible without closures, it can be done even in Pascal and Java! – Blaisorblade Jan 19 '12 at 18:46
8

The below answer was to the original wording which was akin to "How to explain closures to a 5-year old."

Take this box of legos; build yourself a nice little space craft. When you go to billy's house and bring your space craft there; with closures you can still can use all the pieces in your box of legos, even though the box was left in your bedroom.

Alan
  • 45,915
  • 17
  • 113
  • 134
  • Thanks! :) But cannot understand how can I `use all the pieces in your box of legos, even though the box was left in your bedroom.` This box is not in the Billy's house and I cannot go to my home from Billy's house immediately. – StepUp Jun 30 '17 at 20:39
  • How a closure is implemented by a language is outside the scope of the question. How is not as important, as what you can do with a closure. – Alan Jul 01 '17 at 00:56
5

If you really need to keep it simple, then a closure is a function with its context. The function in the closure can still access the same variables it could when it was defined, no matter where you call it from. (In Lua, these are called upvalues, which I think is a very descriptive term.)

I met the concept first in Lua, and this definition helped me understand the concept. Maybe have a look at Lua: its simpleness and power is fascinating, and certainly helps to develop a certain view at other languages. Its concept of closures would be a good example to that.

AttishOculus
  • 1,439
  • 1
  • 11
  • 18
4

If the 5 year old knew C#, I would explain with this code sample:

int i = 0;
string result = null;
Action iExaminer = () =>
{
  result = i % 2 == 1 ? "Odd" : "Even";
};
i = 1;
iExaminer();
Console.WriteLine(result);

If the 5 year old was learning linq, I would explain with this code sample:

string name = null;
IEnumerable<Customer> query = Customers.Where(c => c.Name == name);
name = "Bob";
 // query is resolved when enumerated (which is now)
 // Where will now call our anonymous method.
foreach(var customer in query)
{
  Console.WriteLine(customer.Name);
}
Amy B
  • 108,202
  • 21
  • 135
  • 185
2

Closure (computer science) says:

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.

Translation:
Closures close/attach the variables around the function, so that that function can be teleported to somewhere else and still use those variables e.g. suppose you are teleported to a remote location but have still access to your coffed mug lying on your table

Example:

function makefunc(x)
{
    return function(){return x}
}

Now using makefunc, you can make many anonymous functions which will return what you pass to makefunc

So if you want a function which returns 10, use makefunc(10)(), though pretty useless way toget back 10 :)

Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
0

When you know how to do something in general, you can specify some (or all) details and get a closure.

For example, you know how to buy ice-cream. Yyou know what to do if you will be in front of any shop. But if you want to go to a particular shop (for example, due to a Sunday discount), you move out of house with the aim of buying ice-cream there. "Buy some ice-cream at a store on the corner" is a closure of "buy some ice-cream". In fact, all these are closures of "buy some ice-cream somewhere":

  • Buy some ice-cream at the corner
  • Buy two ice-creams
  • Buy two ice-creams at the corner

Now go play with your friends, son! (and I bear in mind not say anything like that in front of the children)

P Shved
  • 96,026
  • 17
  • 121
  • 165
0

This is a simple approach to the idea in C#: Closure