1

http://msdn.microsoft.com/en-us/library/bb763133.aspx

Module Module1
    Sub Main()
        Dim array1 As Func(Of Integer)() = New Func(Of Integer)(4) {}

        For i As Integer = 0 To 4
            array1(i) = Function() i
        Next

        For Each funcElement In array1
            System.Console.WriteLine(funcElement())
        Next

    End Sub
End Module

It says the result will always be 5 namely the final value of i. How come?

They don't put the iteration variable in the "closure"?

1

1 Answer 1

4

The problem occurs because lambda expressions do not execute when they are constructed but rather when they are invoked.

See the link below: http://blogs.msdn.com/b/vbteam/archive/2007/07/26/closures-in-vb-part-5-looping.aspx

Hope it helps.

Sign up to request clarification or add additional context in comments.

3 Comments

you mean the closure of the lambda expression all contain the same pointer to the same variable i? Is that how it works?
@JimThio: Correct. Lambdas close over variables, not over values. Note that we are changing this behaviour slightly in C# 5. I do not recall if a similar change is being made in VB.
Wow you're from microsoft? Tell Bill Gates I say hi. I am a fan.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.