Iterators and Yield

Iterators produce values lazily (on demand). Yield can appear inside Try...Finally (but not in Catch).

VB doesn't support IAsyncEnumerable iterators (Await For Each) in its syntax. Consume them via the enumerator APIs.

Public Iterator Function Fibonacci(count As Integer) As IEnumerable(Of Long)
    Dim a As Long = 0, b As Long = 1
    For i = 1 To count
        Yield a
        Dim temp = a + b
        a = b
        b = temp
    Next
End Function

Public Iterator Function ReadLinesLazily(path As String) As IEnumerable(Of String)
    Using reader As New IO.StreamReader(path)
        Dim line = reader.ReadLine()
        While line IsNot Nothing
            Yield line
            line = reader.ReadLine()
        End While
    End Using
End Function

For Each f In Fibonacci(10)
    Console.Write($"{f} ")
Next

' Iterator lambda
Dim evens = Iterator Function() As IEnumerable(Of Integer)
                For i = 0 To 10 Step 2
                    Yield i
                Next
            End Function

' Custom collection supporting For Each
Public Class NumberRange
    Implements IEnumerable(Of Integer)
    Private ReadOnly _start, _end As Integer
    Public Sub New(start As Integer, [end] As Integer)
        _start = start : _end = [end]
    End Sub
    Public Iterator Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
        For i = _start To _end
     
…