Home >Backend Development >C++ >Why Do C# Loop Actions Capture the Same Variable, and How Can This Be Avoided?

Why Do C# Loop Actions Capture the Same Variable, and How Can This Be Avoided?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-02-03 07:44:16582browse

Why Do C# Loop Actions Capture the Same Variable, and How Can This Be Avoided?

The variables in the cycle capture

In C#, when defining the operation in the cycle, be sure to pay attention to the behavior of variable capture. By default, all operations capture the same variable, causing the output results to not meet the expected when calling.

Please consider the following example:

The expected output of this code is 0, 2, 4, 6, and 8. However, the actual output is five 10. This is because all operations quote the same captured variable
<code class="language-csharp">List<Action> actions = new List<Action>();

int variable = 0;
while (variable < 5)
{
    actions.Add(() => Console.WriteLine(variable * 2));
    ++variable;
}

foreach (var act in actions)
{
    act.Invoke();
}</code>
, which is updated in the cycle. When calling, all operations have the same value 10.

variable In order to avoid this problem and ensure that each operation instance has its own capture variable, you need to copy the variable in the cycle:

Through the local copy of the variable, each operation captures its own unique value, so as to obtain the expected output 0, 2, 4, 6, 8.
<code class="language-csharp">while (variable < 5)
{
    int copy = variable;
    actions.Add(() => Console.WriteLine(copy * 2));
    ++variable;
}</code>

The concept of this variable capture is critical to understanding the closure of C#. When defining operations within the cycle, be sure to consider the life cycle of the variable and its accessibility.

The above is the detailed content of Why Do C# Loop Actions Capture the Same Variable, and How Can This Be Avoided?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn