Closures in VB Part 3: Scope

Jared here again. For previous articles in this series please see

Thus far in the series we’ve only lifted variables that are declared in the same block/scope. What happens if we lift variables in different scope? The answer is that one closure class will be created for every unique scope where a lifted variable is declared and all of the variables in that scope that are lifted will be placed in that closure. Once again, examples speak best

The code will end up looking like so …

There are a couple of items to take away from this example.

  1. Only two closure classes were created even though three variables were lifted. The number of closures only depends on the number of scopes of all of the lifted declared variables.
  2. The closures are created at the begining of the scope they are associated and not at the begining of the method. This will be more important in the next part of the series.
  3. Each lambda instance is attached to the closure associated with the scope the lambda is declared in.

The next twist is what were to happen if the lambda “f2” were to also use the variable “x”. As it’s currently written there is no association between Closure1 and Closure2 therefore there is no way for it to access the lifted variable. The answer is two fold. Firstly to reduce clutter I pasted the closure classes as if they were separate entries. In fact Closure2 would appear as a nested class of Closure1 in the real generated code.

Secondly if x were used inside of “f2”, the real use would be “c1.x”. That’s (almost) no different than “someOtherVar.x”. Therefore the instance of c1 will be lifted into Closure2.

Woud result in the following definition of Closure2 …

In deeply nested lambdas and scopes this type of lifting will continue recursively.

read original

One thought on “Closures in VB Part 3: Scope

Leave a Reply

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