Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Iterators for VB

Iterators for VB

This item in japanese


Visual Basic's Paul Vick recently revealed a proposal to add iterators in a yet unnamed version. While meant to address the same use cases as C#'s yield return statement, the proposal looks more like something out of a function programmer's playbook.

C#'s iterator is a form of continuation, a rarely used technique popular in languages such as Scheme. Looking at the source, it appears as though the function is interrupted each time a value is returned. The function then picks up from where it left off the next time a value is requested. Behind the scenes, this is done by turning the function into a class with an internal state machine. A decompilation of the class reveals the somewhat extensive bookkeeping needed to pull this off.

Visual Basic's Iterators, look more like an anonymous function. The IEnumerable function will generally begin with a "Return Iterator" block, which is a special case of VB's new anonymous, multi-line function syntax. From within this block one may make calls to Return and Return Each.

A Return statement within an anonymous Iterator works just like C#'s yield return. The "yield" keyword is not needed because it is implied by the context.

A Return Each statement effectively "unwraps" a collection, returning the values one at a time.

VB's syntax has some advantages over the C# version. Since it is implemented as an anonymous function within another function, one could do some preliminary checks and calculations before creating the iterator. It would not be out of line to find multiple iterator implementations in one method, the specific one returned being determined at runtime.

One could also foresee custom iterators being created and used entirely within the scope of a function. This would be especially useful when turning an arbitrary data structure into something that can be operated on via the LINQ query notation.

Rate this Article