Lexical Closures in VB 9

Must read for everyone who is developing in VB! Jared Parsons tells us what he think closure is: “A closure is a feature which allows users to seemlessly access an environment (locals, parameters and methods) from more than one function.

and here are some samples:

In this code we have a lambda expression which takes in a single parameter and adds it with a local variable. Lambda expressions are implemented as functions in VB (and C#). So now we have two functions, “Test” and “f”, which are accessing a single local variable. This is where closures come into play. Closures are responsible for making the single variable “x” available to both functions in a process that is referred to as “lifting the variable”.

To do this the compiler will take essentially 4 actions.

1. Create a class which will contain “x” in order to share it among both functions. Call it “Closure” for now
2. It will create a new function for the lambda expression in the class “Closure”. Call it “f” for now
3. Create a new instance of the class “Closure” inside the sub “Test”
4. Rewrite all access of “x” into the member “x” of “Closure”.
view original

Leave a Reply

Your email address will not be published. Required fields are marked *