[RESOLVED] Lambda Expression Confusion
Hi all,
I've been wondering about lambda expressions for a while now.
Consider the following code
vb.net Code:
Sub Main()
Dim I As Integer
SomeUselessSub(Sub()
Dim K As Integer = I
End Sub)
SomeUselessSub(New Action(AddressOf DoSomething))
End Sub
Sub DoSomething()
End Sub
Sub SomeUselessSub(ByVal D As [Delegate])
End Sub
Both
Code:
SomeUselessSub(Sub()
Dim K As Integer = I
End Sub)
And
Code:
SomeUselessSub(New Action(AddressOf DoSomething))
Are valid calls to SomeUselessSub.
But in the lambda expression I have access to all Sub Main's variables. Is it safe to use them ?
Re: Lambda Expression Confusion
Since you can only use those variables in the lambda when calling the lambda from Sub Main, I would say yes it is safe to use them. It is really no different than passing them in as byref parameters (for value types) or simply just passing them in (for reference types).
Re: Lambda Expression Confusion
I suspected as much. Thanks for confirming :D
Re: [RESOLVED] Lambda Expression Confusion
Just be aware that the value of the 'captured' local will be the value when the lambda is invoked, not declared.
e.g.
Code:
Dim I As Integer = 0
Dim o = Sub()
Dim K As Integer = I
End Sub
I = 1
o() 'K within the lambda will be assigned 1, not 0