Home >Backend Development >C++ >How Can I Prevent Lambda Expressions from Capturing References in C#?

How Can I Prevent Lambda Expressions from Capturing References in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-19 00:01:09168browse

How Can I Prevent Lambda Expressions from Capturing References in C#?

Preventing Reference Capture in C# Lambda Expressions

C# lambda expressions, by default, capture variables by reference. This means the lambda expression maintains a pointer to the original variable, and any changes to that variable after the lambda's creation will be reflected when the lambda is executed.

Here's an example illustrating this behavior:

<code class="language-csharp">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>

Executing this code will print "10" ten times. This happens because each lambda captures a reference to the single i variable, whose value is 10 by the time the loop finishes.

To avoid this reference capture and ensure each lambda gets its own copy of the loop variable's value, create a local copy within the loop:

<code class="language-csharp">for (int i = 0; i < 10; i++)
{
    int copy = i; // Create a local copy
    actions.Add(() => Console.WriteLine(copy));
}</code>

Now, each lambda captures a distinct copy variable, preserving the value at the time of its creation. The output will correctly display numbers 0 through 9.

It's crucial to understand that unlike some other languages (like C ), C# doesn't offer a direct mechanism to explicitly specify reference or value capture within the lambda expression syntax itself. Creating a local copy is the standard workaround to achieve value-capture semantics.

The above is the detailed content of How Can I Prevent Lambda Expressions from Capturing References in C#?. 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