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?
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:
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 ofdata
be at the time? Will it even be valid? This is especially dangerous if you useyield return
.A simpler example, without an iterator, is: