Closures/Value capture: Difference between revisions
Content added Content deleted
(Added another C# example that doesn't use Linq) |
(Added some comments to explain how we avoid the closure trap) |
||
Line 166: | Line 166: | ||
for ( int i = 0; i < 10; ++i ) |
for ( int i = 0; i < 10; ++i ) |
||
{ |
{ |
||
// This is key to avoiding the closure trap, because |
|||
// the anonymous delegate captures a reference to |
|||
// outer variables, not their value. So we create 10 |
|||
// variables, and each created anonymous delegate |
|||
// has references to that variable, not the loop variable |
|||
var captured_val = i; |
var captured_val = i; |
||
l.Add( delegate() { return captured_val * captured_val; } ); |
l.Add( delegate() { return captured_val * captured_val; } ); |