Home >Backend Development >C++ >How Do I Prevent Unexpected Behavior When Capturing Variables in C# Lambda Expressions?
Understanding C# Lambda Expression Variable Capture
C# lambda expressions offer a compact way to define anonymous functions. However, their interaction with variables in the surrounding scope can be tricky.
The Problem: Shared Variable Modification
Let's examine a common issue. The following code aims to create a list of actions, each printing a different counter value:
<code class="language-csharp">List<Action> actions = new List<Action>(); for (int i = 0; i < 10; i++) { actions.Add(() => Console.WriteLine(i)); } foreach (Action a in actions) a();</code>
Surprisingly, this prints "10" ten times. The lambda captures a reference to i
, not its value. As the loop modifies i
, all lambdas see the final value.
The Solution: Capturing by Value
C# doesn't directly support capture-by-value syntax like C 0x's [=]
. The workaround is to create a local copy within the loop's scope:
<code class="language-csharp">for (int i = 0; i < 10; i++) { int copy = i; // Create a local copy actions.Add(() => Console.WriteLine(copy)); }</code>
Now, each lambda captures a separate copy
variable, preserving the correct value for each iteration.
Why Local Copies Matter
The difference lies in variable scope. A reference shares the same memory location; changes are immediately reflected. A copy creates an independent snapshot of the variable's value at the time of capture. Subsequent changes to the original variable are irrelevant to the lambda's captured copy.
The above is the detailed content of How Do I Prevent Unexpected Behavior When Capturing Variables in C# Lambda Expressions?. For more information, please follow other related articles on the PHP Chinese website!