Why I get: "An iteration variable in a lambda expression may have unexpected results"

Possible duplicate:
Why is it bad to use an iteration variable in a lambda expression

Why do I get: "An iteration variable in a lambda expression can have unexpected results"? Suppose I have the following code:

Dim writeAbleColumns As String() = {"IsSelected", "IsFeeExpense", "IsSubscriptionRedemption"} With grid For Each column As DataGridViewColumn In .Columns column.ReadOnly = Not Array.Exists(writeAbleColumns, Function(arrElement) column.Name = arrElement) Next End With 

I get a warning:

 Warning 1 Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable. 

I do not understand why changing my code to the following changes:

  Dim writeAbleColumns As String() = {"IsSelected", "IsFeeExpense", "IsSubscriptionRedemption"} With grid For Each column As DataGridViewColumn In .Columns Dim c As DataGridViewColumn = column column.ReadOnly = Not Array.Exists(writeAbleColumns, Function(arrElement) c.Name = arrElement) Next End With 

In principle, nothing changes except a warning. I just have another variable pointing to my variable. Why a warning? What unexpected things can happen?

+4
source share
2 answers

A lambda is bound to a variable, not to the value of a variable when the lambda was converted to a delegate. When the loop variable is updated, each lambda associated with that variable also sees the changed value of the variable, which you might not need. Creating a new variable each time the loop repeats binds each lambda over a new, different, immutable variable.

This is the main point of pain in C # and VB. In C # 5 and VB 11, we are changing the semantics of loop closure to mitigate this problem.

For more information see

Is there a reason for reusing a C # variable in foreach?

and the last few paragraphs of Tim’s article:

http://msdn.microsoft.com/en-us/magazine/cc163362.aspx

and my article:

http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/

+15
source

In your case, nothing can go wrong.

The problem is that this lambda will be saved and used after the loop continues (for example, used in the event handler). Eric Lippert has a very nice explanation on his blog .

Oh, and this question already has a very long list of links here on SO.

+4
source

Source: https://habr.com/ru/post/1399263/


All Articles