BT

InfoQ Homepage News Limitations of Closures in Visual Basic

Limitations of Closures in Visual Basic

Bookmarks

In part 6 of his series on closures, Jared Parsons takes about some of the limitations of closures in Visual Basic. While it is not explicitly called out, many of these limitations may also apply to C#.

To understand closures, one first has to understand anonymous functions. An anonymous function is defined within the context of another function, usually by assigning it to a delegate variable.

In order to share data between anonymous functions and the function that contains them, it is common to use closures. When a closure "captures" a variable it "lifts" the variable out of its local scope and effectively moves it into an anonymous object. In the case of member variables, a simple reference is kept to the containing object. While most local and member variables can be lifted, but there are restrictions.

The first restriction is against lifting ByRef parameter variables. While ByVal parameters are effectively local variables, ByRef variables have to copy their value back to the calling method under all circumstances. While doing this is trivial for normal parameters, it is very hard to make that guarantee with a closure.

The second limitation is that member variables of structures cannot be raised. Because structures, also known as value types, can appear on the stack, it is not always possible to create a pointer to them. The best one could do is to create a pointer to a copy of the structure, which defeats the purpose of having a closure.

Note that variables that contain entire structures can be captured. It is only the member variables within a structure accessed via the "Me" keyword that cannot be used.

Certain restricted types such as System.TypedReference, System.ArgIterator, and System.RuntimeArgumentHandle cannot be captured. As these are not used in most programs, it should not affect anyone.

Because of the scoping rules for closures, one cannot use a goto to enter a block of code containing a closure. Finally, the legacy statement On Error GoTo cannot be used at all in a method containing closures.

Rate this Article

Adoption
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

BT

Is your profile up-to-date? Please take a moment to review and update.

Note: If updating/changing your email, a validation request will be sent

Company name:
Company role:
Company size:
Country/Zone:
State/Province/Region:
You will be sent an email to validate the new email address. This pop-up will close itself in a few moments.