What difference between
static Func<int> Natural()
{
int seed = 0;
return () => seed++; // Returns a closure
}
and
static Func<int> Natural()
{
return() => { int seed = 0; return seed++; };
}
Why
static void Main()
{
Func<int> natural = Natural();
Console.WriteLine (natural());
Console.WriteLine (natural());
}
shows 0 1 for first Natural() and 0 0 for second one? Thanks!
The difference is that in the first version, you're declaring a variable and then capturing the variable in the lambda expression. The variable itself "survives" across multiple invocations of the delegate.
In the second example, you're declaring a variable inside the lambda expression, so every time the delegate is executed, the variable effectively starts again.
To put it another way, it's the difference between:
class NaturalImpl
{
public int seed;
public int Method()
{
return seed++;
}
}
Func<int> natural = new NaturalImpl().Method;
and:
class NaturalImpl
{
public int Method()
{
int seed = 0;
return seed++;
}
}
Func<int> natural = new NaturalImpl().Method;
Note the difference between the instance variable in the first version, and the local variable in the second.
(That's not exactly what the implementation of the second form would look like; it would be a static method in the enclosing class as it's stateless, but...)
See more on this question at Stackoverflow