How to use external variables in c# lambda functions?
In C#, if you want to use an external variable in a lambda expression, you can achieve this by capturing the variable. There are two ways to capture variables.
1. Using by reference capture: when using external variables in a lambda expression, the variables will be captured by reference. This means that if the value of the variable is modified outside of the lambda expression, it will also be reflected inside the lambda expression.
int x = 10;
Action action = () => Console.WriteLine(x);
x = 20;
action(); // 输出结果为20
2. Value capture: When using external variables in a lambda expression, the current value of the variable will be captured by value. This means that if the variable’s value is changed outside the lambda expression, it will not be affected inside the lambda expression.
int x = 10;
Action action = () =>
{
int y = x;
Console.WriteLine(y);
};
x = 20;
action(); // 输出结果为10
It is important to note that for reference type variables, both reference capture and value capture will capture the reference of the variable. This means that if the properties or fields of a reference type variable are modified within a lambda expression, it will affect the original variable.
List<int> numbers = new List<int> { 1, 2, 3 };
Action action = () =>
{
numbers.Add(4);
Console.WriteLine(numbers.Count);
};
action(); // 输出结果为4
Console.WriteLine(numbers.Count); // 输出结果为4
In conclusion, lambda expressions with external variables can be achieved through either reference capture or value capture, depending on the type of variable and requirements.