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
Release: 2025-02-03 07:59:09
Original
874 people have browsed it

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.
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();
}
Copy after login

<:> 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.

while (variable < 5)
{
    int copy = variable;
    actions.Add(() => Console.WriteLine(copy * 2));
    ++variable;
}
Copy after login
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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template