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.
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.
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.
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."
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.
The below answer was to the original wording which was akin to "How to explain closures to a 5-year old."
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:
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 :)
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.