Home >Backend Development >C++ >Why Does My C# Loop Capture the Wrong Variable Value?

Why Does My C# Loop Capture the Wrong Variable Value?

Susan Sarandon
Susan SarandonOriginal
2025-02-03 07:59:09843browse

Why Does My C# Loop Capture the Wrong Variable Value?

Cover variable in the cycle: a strange problem

When using the C#cycle, you may encounter a special problem to capture variables. Let's consider the following scenes:

In contrast to expected, this code prints five "10" instead of the expected sequence 0, 2, 4, 6, 8.
<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>

Question: The capture variable in the cycle

All Lambda functions created in the cycle capture the same variable . Therefore, when these functions are called outside, they all quote the final value of

.

variable Solution: Copy rescue variable

In order to solve this problem, you need to create a copy of the variable in the cycle, and then capture it in each lambda function:

By creating a copy, each closure created in the cycle will capture its own

unique value, thereby generating expected output.

<code class="language-csharp">while (variable < 5)
{
    int copy = variable;
    actions.Add(() => Console.WriteLine(copy * 2));
    ++variable;
}</code>
Precautions

variable

Please note that this technology is also applicable to the for and foreach cycle, which references a single variable in multiple iterations. To avoid this problem, it is recommended to obey the C# 5 compiler's processing method of the Foreach cycle, which ensures that each iteration has its own capture variable.

The above is the detailed content of Why Does My C# Loop Capture the Wrong Variable Value?. 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