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


== Noncompliant Code Example

----
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

----
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

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


ifdef::rspecator-view[]
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::rspecator-view[]
