9

Possible Duplicate:
What is a 'Closure'?
Access to Modified Closure
Access to Modified Closure (2)

Resharper is complaining about the following piece of code:

foreach (string data in _dataList)
    DoStuff (() => field);

What is a closure? And why should I care?

I've read about closure in maths and functional programming and I'm at a loss here. Too heavy for my brain.

In simpler terms, what is going on here?

Community
  • 1
  • 1
Golem
  • 115
  • 1
  • 5
  • possible duplicate of [Access to Modified Closure (2)](http://stackoverflow.com/questions/304258/access-to-modified-closure-2) or [Access to Modified Closure](http://stackoverflow.com/questions/235455/access-to-modified-closure?rq=1) – jrummell Jul 18 '12 at 13:39
  • 2
    Well, these don't help understand what is a closure... :( – Golem Jul 18 '12 at 13:41
  • 1
    perhaps then reword the title of your question to "What is a Closure?" – hometoast Jul 18 '12 at 13:45
  • How about this one: [What is a 'Closure'?](http://stackoverflow.com/questions/36636/what-is-a-closure) – jrummell Jul 18 '12 at 13:45
  • in which case these would be duplicates of your question: http://stackoverflow.com/questions/3805474/what-is-a-closure-does-java-have-closures http://stackoverflow.com/questions/36636/what-is-a-closure – hometoast Jul 18 '12 at 13:47

1 Answers1

9

Here is a fairly good explanation.

A closure is created when you reference a variable in the body of a method from a delegate. Essentially, a class that contains a reference to the local variable is generated.
If the variable is constantly modified, when an external method calls the delegate, it may contain an unpredictable value, or even throw an exception. For example, in an example like this:

foreach (string data in _dataList)
{
    DoStuff (() => data);
}

The method () => data is always going to be the same method. if you store it, you don't know what happens when it's eventually invoked -- what will the value of data be at the time? Will it even be valid? This is especially dangerous if you use yield return.

A simpler example, without an iterator, is:

var x = 5;
Action f = () => Console.WriteLine(x);
x = 76;
f();
Louis Hong
  • 1,051
  • 2
  • 12
  • 27
GregRos
  • 8,667
  • 3
  • 37
  • 63