Iterators in VB 10 ?

Although VB 10 won’t have a formal syntax for iterators, it will have all the necessary ingredients to easily write iterators. In VB10 you can use a generic template and multi line lambdas to create iterators.

This iterator in C# :


static public IEnumerable<String> Lines( this TextReader rdr)
     String line;
     while ((line = rdr.ReadLine()) != null)  {
              yield return line; 


Can be written as this in VB10:

Public Function Lines(ByVal rdr as TextReader) As IEnumerable(Of String)
     Return New GenericIterator(Of String) 
          (Function(ByRef nextItem As String) As Boolean
              nextItem = rdr.ReadLine
              Return nextItem IsNot Nothing
           End Function)
End Function

The above code uses a generic iterator class that accepts a lambda function. The lambda function sets the Current item of the iterator and returns True if MoveNext should be True. The above example is written as an extension method, but you can also use the inner part of the function inline.

For more on using iterators in VB 9 today, as well as the generic class for the above example, see my latest article in Visual Studio Magazine .

1 Comment so far

  1.   Rory Becker on February 25th, 2009          

    I’d still like a yield keyword