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:

<Extension()> 
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 .

This entry was posted in 4219, 491, 5726, 6183, 7099, 7341, 8917. Bookmark the permalink.

One Response to Iterators in VB 10 ?

  1. Rory Becker says:

    I’d still like a yield keyword

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>