Home > Backend Development > C++ > Why Do C# Loops with Captured Variables Produce Unexpected Results?

Why Do C# Loops with Captured Variables Produce Unexpected Results?

Mary-Kate Olsen
Release: 2025-02-03 08:20:10
Original
210 people have browsed it

Why Do C# Loops with Captured Variables Produce Unexpected Results?

In -depth discussing the problem of capturing variables in the C# cycle

In C#, developers encounter an interesting problem when using capture variables in cycle iteration. Consider the following code fragment:

Although the expected output is 0, 2, 4, 6, and 8, the code unexpectedly output five 10. The reason for this behavior is the captured variables
<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)
{
    Console.WriteLine(act.Invoke());
}</code>
Copy after login
. All operations quote the same examples of . When variables change in the cycle, this may lead to unpredictable results.

variable Solve the problem of capture variables variable

In order to overcome this limit and allow each operation to have its own capture variables, C# provides a simple solution:

By creating a copy of the

in the cycle, each operation captures its own sole examples, so as to ensure that

changes outside the lambda expression will not affect the capture value.
<code class="language-csharp">while (variable < 5)
{
    int copy = variable;
    actions.Add(() => Console.WriteLine(copy * 2));
    ++variable;
}</code>
Copy after login

Other common situations variable variable

This problem may also appear in other scenarios involving variables in the cycle, such as

and iteration:

In these two cases, the local copy of the variable is required to capture the current cycle iteration. for foreach Conclusion

<code class="language-csharp">// For loop
for (int i = 0; i < 5; i++)
{
    // ... similar issue ...
}

// Foreach loop
// ... similar issue ...</code>
Copy after login

Understanding the behavior of capturing variables in the C# cycle is essential to avoid accidents. The solution discussed in this article ensures that each operation has its own independent capture variables, thereby achieving predictable and expected behaviors.

The above is the detailed content of Why Do C# Loops with Captured Variables Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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