Edit: Here is a much more simpler example of this issue (i've deleted my original question):
Dim numbers1 As New List(Of Int32)({1, 2, 3})
Dim numbers2 As New List(Of Int32)({3, 4, 5})
For Each n1 In numbers1
' no warning '
Dim contains = numbers2.Contains(n1)
Next
For Each n1 In numbers1
' warning on n1'
Dim contains = (From num In numbers2 Where num = n1).Any
Next
So i still don't understand why the compiler thinks that i may get unexpected results in the second iteration whereas i'm safe with the first. I don't think that the interesting link of @ee-m provides the reason for this behaviour,(this is not a for-each
issue, For n1 As Int32 = 1 To 3
would also result in a compiler warning).
I'm not really convinced that following should be "best-practice":
For Each n1 In numbers1
Dim number1 = n1
' no warning'
Dim contains = (From num In numbers2 Where num = number1).Any
Next
The local variable number1
is redundant and makes the code less readable as @Meta-Knight already has emphasized. Note: All three ways are safe and give the correct result.