I was checking that the position of variable declarations in VB.NET don't matter, except for scope, (for this question) and I thought I better check what happens when they're "lifted" into a closure. I haven't read the spec, but I can't explain these results:
Dim outer As Integer
For i = 1 To 2
Dim inner As Integer
Try
Dim inner2 As Integer
Do
Dim inner3 As Integer
Call Sub()
Dim inner4 As Integer
Console.WriteLine(outer & ", " & inner & ", " & inner2 & ", " & inner3 & ", " & inner4)
outer = i
inner = i
inner2 = i
inner3 = i
inner4 = i
End Sub()
Loop Until True
Finally
End Try
Next
The above outputs:
0, 0, 0, 0, 0
1, 1, 0, 1, 0
inner4
being reset each time makes sense, as would all or none of the other innerX
, but why only inner2
?!
(This is more a comment, but in need of too much code to keep it as one.)
Reflector does show what is happening:
(This is based upon my code which includes a
Try
outside theFor
.)You can see here the
For
loop (seen as aDo
loop with the$VB$Local_i
set before) and the innerDo
generate closures that do have the previous instance of the closure passed in, but theTry
does not get that treatment.Still don't know why? Looks like a bug to me. If I don't get a reasonable "excuse" (:-)) in a day or so I'll put it on Connect. (Can someone confirm .NET 4.5 VB11 performs the same?)
From MSDN (emphasis mine) :
Link