== Why is this an issue?

Once you modify a closure, any use of it could provide unexpected results.


=== Noncompliant code example

[source,csharp]
----
var x = 0;
Func<int> f1 = () => x;  // Noncompliant
x = 1;
Console.WriteLine(f1());

var input = new[] { 1, 2, 3 };
var fs = new List<Func<int>>();
for (var i = 0; i < input.Length; i++) {
  Func<int> f = () => input[i];  // Noncompliant
  fs.Add(f);
}
Console.WriteLine(fs[0]()); //Access to modified closure yields Exception
----


=== Compliant solution

[source,csharp]
----
var x = 0;
var xx = x;
Func<int> f = () => xx;
x = 1;
Console.WriteLine(f());

var input = new[] { 1, 2, 3 };
var fs = new List<Func<int>>();
for (var i = 0; i < input.Length; i++) {
  var ii = i;
  Func<int> f = () => input[ii];
  fs.Add(f);
}
Console.WriteLine(fs[0]());

----
or

[source,csharp]
----
var input = new[] { 1, 2, 3 };
var fs = input.Select(t => (Func<int>) (() => t)).ToList();
Console.WriteLine(fs[0]());
----


ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Remove the access to the modified closure.


'''
== Comments And Links
(visible only on this page)

=== on 20 Mar 2015, 16:08:06 Ann Campbell wrote:
\[~tamas.vajk] is the problem really in accessing the modified closure, or is the problem that the closure was modified at all?

=== on 23 Mar 2015, 07:28:58 Tamas Vajk wrote:
\[~ann.campbell.2] the problem is that the closure was modified, and then it was used.

=== on 8 Jun 2015, 11:44:37 Tamas Vajk wrote:
\[~ann.campbell.2] this RSPEC doesn't seem to be finished, it is missing a lot of metadata (sqale, severity, ...)

=== on 8 Jun 2015, 12:27:22 Ann Campbell wrote:
Sorry about that [~tamas.vajk]. Take a look now.

Also, I've set this rule to Blocker. Do you think that's too severe?

=== on 9 Jun 2015, 06:53:16 Tamas Vajk wrote:
\[~ann.campbell.2] Thanks, it looks good. The blocker severity seems okay, the rule detects bugs.

endif::env-github,rspecator-view[]
