I am reading about lambda expressions, and I've seen this example,
Example 1:
static Func<int> Natural()
{
int seed = 0;
return () => seed++; // Returns a closure
}
static void Main()
{
Func<int> natural = Natural();
Console.WriteLine (natural()); // output : 0
Console.WriteLine (natural()); // output : 1
}
Example 2:
static Func<int> Natural()
{
return() => { int seed = 0; return seed++; };
}
static void Main()
{
Func<int> natural = Natural();
Console.WriteLine (natural()); // output : 0
Console.WriteLine (natural()); // output : 0
}
I am not able to understand why first example output is 0 and 1.
Because the initialization code in the second example (int seed = 0) is run at each invocation.
In the first example, seed is a captured variable that exists beyond the method, since there is only one instance its value is kept between invocations.
UPDATE: In response to David Amo's comment, an explanation.
Option 1)
static Func<int> Natural()
{
int seed = 0;
return () => seed++; // Returns a closure
}
Option 2)
static Func<int> Natural()
{
return() => { int seed = 0; return seed++; };
}
Option 3)
static Func<int> Natural()
{
int seed = 0;
return () => { seed = 0; return seed++;}; // Returns a closure
}
Option 3 returns the same value that option 2, but internally works as option 1. seed is a variable defined inside Natural, but since it is captured by the delegate it continues to exist after the method has exited.
Another test that you may use to see what is happening is
static Func<int> Natural()
{
int seed = 1;
Func<int> returnValue = () => { return seed++; };
seed = 2;
return returnValue;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With