Home  >  Article  >  Backend Development  >  Why Does My Lambda Expression Capture the Last Value of a Loop Variable?

Why Does My Lambda Expression Capture the Last Value of a Loop Variable?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 22:50:02657browse

Why Does My Lambda Expression Capture the Last Value of a Loop Variable?

Capturing Variables in Lambda Expressions Within Loop Iterations

The code snippet demonstrates the unexpected behavior when using the iterator variable of a foreach loop in a lambda expression. Upon execution, instead of printing "Hi String," "Hi Single," and "Hi Int32," it prints "Hi Int32" for all three methods.

Explanation

This behavior stems from the nature of lambda expressions and their captured variables. When a lambda expression is defined inside a loop, it captures the loop variable's reference, not its value. As a result, it refers to the same variable throughout the loop's iterations.

In the provided code, the variable type is captured by the lambda expression. However, the code does not account for the fact that the same reference to type will be shared among all iterations of the loop. Consequently, each lambda expression ends up capturing the value of type from the last iteration, resulting in the unexpected printouts.

Correction

To resolve this issue and achieve the desired goal, you need to ensure that each lambda expression captures a unique value of type. To do this, create a new variable for each iteration, assigning it the current value of type:

foreach (var type in types)
{
   var newType = type;
   var sayHello = 
            new PrintHelloType(greeting => SayGreetingToType(newType, greeting));
   helloMethods.Add(sayHello);
}

By using newType, you effectively create a copy of type, capturing its value from the current iteration. This ensures that each lambda expression has a unique reference to its own value of type, leading to the correct output.

The above is the detailed content of Why Does My Lambda Expression Capture the Last Value of a Loop Variable?. 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