Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
int bonus = 10;
Func<int, int> add = x => x + bonus;
Console.WriteLine(add(1));
bonus = 20;
Console.WriteLine(add(1));11 21
- Expecting
11 11: a lambda does not copybonuswhen it is created; it holds the variable and reads its current value at each call. - Expecting a closure to see only the variable's final value: each call reads the value it has at the moment of that call.
- What changes in the output if the lambda itself runs
bonus++before returning? - Why do lambdas created in a
forloop that captureiall return the same number?