Closures/Value capture: Difference between revisions
Content added Content deleted
(Added another C# example that doesn't use Linq) |
|||
Line 126: | Line 126: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
===Using Linq=== |
|||
<lang csharp>using System; |
<lang csharp>using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 151: | Line 152: | ||
49 |
49 |
||
64</lang> |
64</lang> |
||
===Using delegates only=== |
|||
<lang csharp> |
|||
using System; |
|||
using System.Collections.Generic; |
|||
class Program |
|||
{ |
|||
static void Main( string[] args ) |
|||
{ |
|||
List<Func<int>> l = new List<Func<int>>(); |
|||
for ( int i = 0; i < 10; ++i ) |
|||
{ |
|||
var captured_val = i; |
|||
l.Add( delegate() { return captured_val * captured_val; } ); |
|||
} |
|||
l.ForEach( delegate( Func<int> f ) { Console.WriteLine( f() ); } ); |
|||
} |
|||
} |
|||
</lang> |
|||
Output: |
|||
<lang>0 |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |