Accessing Varibles outside a Lambda (C#)

时间:2022-06-01 20:20:19

Lambda expression offers a way to wrap a function without complex definitions.

The compiler creates an anonymous class for a Lambda expression at runtime and creates an instance when it is called. Any variable accessed insided the Lambda will be accessed at the time the instance is created.

int v = 3;
Func<int, int> f = s => s+v;
v = 5;
WriteLine($"The return value of f(0) is {f(0)}");

You may expect a 5 instead of 3.