can someone explain to me how access to vars in anonymous functions is handled?
having the following:
Code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim btn As New Button
Controls.Add(btn)
Dim i As Int32 = 1
AddHandler btn.Click, Sub() MessageBox.Show(i.ToString)
btn = New Button With {.Top = 20}
Controls.Add(btn)
i = 2
AddHandler btn.Click, Sub() MessageBox.Show(i.ToString)
End Sub
both buttons showing "2" suggests that i is compiled byref in both anonymous functions, so the compiled code of both subs contains a pointer to i, right? but that would mean that i is preserved even when Form1_Load is exited, something that goes against the normal var scope rules. one other explanation for the observed behaviour would be that both subs are only compiled at the end for Form_Load, but that seems odd as well.
If the second "i" is replaced by "j", then the behaviour is that one button shows "1", the other "2".
then this one:
Code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim btn As New Button
Controls.Add(btn)
Dim o As New Dummy With {.Value = 1}
AddHandler btn.Click, Sub() MessageBox.Show(o.Value.ToString)
btn = New Button With {.Top = 20}
Controls.Add(btn)
o = New Dummy With {.Value = 2}
AddHandler btn.Click, Sub() MessageBox.Show(o.Value.ToString)
End Sub
Private Class Dummy
Property Value As Int32
End Class
suggests that "o" (which itself is a reference to a class instance) within the anonymous subs is byref, wait, that gives me an idea, how about this:
Code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim btn As New Button
Controls.Add(btn)
Dim o As New Dummy With {.Value = 1}
AddHandler btn.Click, Sub() MessageBox.Show(o.Value.ToString)
btn = New Button With {.Top = 20}
Controls.Add(btn)
o = New Dummy With {.Value = 2}
AddHandler btn.Click, Sub()
o.Value += 1
MessageBox.Show(o.Value.ToString)
End Sub
End Sub
Private Class Dummy
Property Value As Int32
End Class
now that is really kind of strange as both subs use the same class instance even though there was a new instance created before the second sub was created. so is it really holding back compilation of anonymous functions until the end of the sub??
thanks for any insight.