Iterators in VB 10 ?

Posted Mon, Feb 2 2009 23:56 by bill

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 .

Filed under: , , , , , ,


# re: Iterators in VB 10 ?

Wednesday, February 25, 2009 5:11 AM by Rory Becker

I'd still like a yield keyword

# using classes vs. modules - Page 3 | keyongtech

Wednesday, February 25, 2009 6:07 AM by using classes vs. modules - Page 3 | keyongtech

Pingback from  using classes vs. modules - Page 3 | keyongtech

# Iterators: a flag for simplification ?

Monday, April 20, 2009 9:02 PM by @ Head

A couple of months ago I blogged about iterators in VB (or the lack there-of), and pointed folks to an