2

I'm trying to understand why, in the following example, the value of 'fac' is the value 2, even after there's an assignment to the value 3.

public class Program
{
    public static void Main()
    {
        int fac = 1;

        Func<int, int> mul = (n) =>
        {
            fac = 2;
            return fac * fac;
        };

        fac = 3;

        Console.WriteLine(mul(fac));
        Console.WriteLine(fac);
    }
}

result:

4

2

I know that lambda expressions can themselves update captured variables (in this case 'fac') but to this extent seems confusing.

1
  • the lambda expression is invoked after setting the value to 3. so last assignment would be 2 Commented Mar 24, 2018 at 12:29

1 Answer 1

5

...the value of 'fac' is the value 2, even after there's an assignment to the value 3.

This statement is not the whole story.

First, fac is assigned to 1. Next, fac is assigned to 3. When you call mul(), fac is assigned to 2.

In all cases, the same variable fac is modified, and the assignment inside mul() doesn't occur until mul() is called.

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

1 Comment

Yeah, you're right. I forgot that captured variables are evaluated when the delegate is invoked, not when captured.

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.