1

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!

2
  • I guess you are also irrated why the second one returns 0 instead of 1, thats because you wrote seed++ this should be changed to ++seed. Commented May 19, 2014 at 12:25
  • In the first example seed is outside the returned function, in the second it's inside the function Commented May 19, 2014 at 12:29

2 Answers 2

11

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...)

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry about rolling that back, I was doubting myself for a second (I previously approved the suggested edit).
3

In the first case, whenever Natural is called it returns a function that refers to the same seed variable each time (the one that's defined inside Natural itself).

In the second case it returns a function that refers to a different seed variable each time (the one that's defined inside the body of said function).

It stands to reason that in the first case each returned function will be able to "see" changes to seed made by the others because all of them are working on the same value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.