This behavior is due to Closures .
The variable that is present in your lambda is a link and not . This means that it points to the last value accepted by str
, which is "ghi" in your case. That is why for each call it simply goes to the same memory location and, naturally, gets the same value.
If you write code, as in the answers provided, you force the C#
compiler to update the new value each time, so a new address will be sent to labmda, so each lambda will have its own variable.
By the way, if I'm not mistaken, the C#
team promises to fix this unnatural behavior in C# 5.0
. Therefore, it is better to check your blog on this topic for future updates.
source share