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
?!
Dim closure = Sub()...End Sub : closure()
and I've tested it and the results are the same.inner3
is the interesting one rather thaninner2
. I think it should be 0.inner2
is reset, I definitely can't see whyinner3
isn't. And clearly theTry
is "special", which is why there's a difference betweeninner
andinner2
. I've also tested aTry
outside theFor
loop and a variable declared there has the same behaviour asouter
.