69 lines
1.2 KiB
Plaintext
69 lines
1.2 KiB
Plaintext
== 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)
|
|
|
|
include::message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|