Home > Backend Development > C++ > Reference vs. Copy in C# Lambda Capture: When Do I Get Unexpected Behavior?

Reference vs. Copy in C# Lambda Capture: When Do I Get Unexpected Behavior?

Patricia Arquette
Release: 2025-01-18 23:56:10
Original
283 people have browsed it

Reference vs. Copy in C# Lambda Capture: When Do I Get Unexpected Behavior?

In-depth understanding of Lambda capture in C#: reference and copy

In C#, Lambda expressions can capture variables in the enclosing scope. When a Lambda captures a reference to a variable, any changes to that variable will be reflected in the Lambda. This can lead to unexpected behavior, as shown in the following code snippet:

<code class="language-C#">class Program
{
    delegate void Action();
    static void Main(string[] args)
    {
        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>
Copy after login

When you run this code, it prints the number 10 ten times. This is because the Lambda function captures a reference to the variable i and when i is incremented in the for loop, the Lambda function still sees the updated value.

To capture a copy of a variable instead of a reference, you can use the following syntax:

<code class="language-C#">[=] () => { ... } // 捕获副本</code>
Copy after login

In this example, the Lambda function will capture a copy of the variable i and any changes to i in the enclosing scope will not be reflected in the Lambda function.

Here is a modified example demonstrating how to capture a copy:

<code class="language-C#">for (int i = 0; i < 10; i++)
{
    int copy = i; // 创建一个局部副本
    actions.Add(() => Console.WriteLine(copy));
}</code>
Copy after login

In this case, the Lambda function will print the value of copy, which is a copy of the value of i when the Lambda function was created.

By understanding the difference between capturing a reference and capturing a copy, you can avoid unexpected behavior in your Lambda functions.

The above is the detailed content of Reference vs. Copy in C# Lambda Capture: When Do I Get Unexpected Behavior?. 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