Friday, September 09, 2011

Closure Example

Example 1:
static Func Natural()
{
int seed = 0;
return () => seed++; // Returns a closure
}
static void Main()
{
Func natural = Natural();
Console.WriteLine (natural()); // 0
Console.WriteLine (natural()); // 1
}


Example 2:


static Func Natural()
{
return() => { int seed = 0; return seed++; };
}


static void Main()
{
Func natural = Natural();
Console.WriteLine (natural()); // 0
Console.WriteLine (natural()); // 0
}

Capturing is internally implemented by “hoisting” the captured
variables into fields of a private class. When the method is
called, the class is instantiated and lifetime-bound to the delegate
instance.

0 Comments:

Post a Comment

<< Home