C# lambda, local variable value not taken when you think?

This is a modified closure

See: similar questions like Access to Modified Closure

To work around the issue you have to store a copy of the variable inside the scope of the for loop:

   foreach(AClass i in AClassCollection) 
   { 
      AClass anotherI= i;
      listOfLambdaFunctions.AddLast(  () =>  {  PrintLine(anotherI.name); }  ); 
   } 

Leave a Comment