Iterators and Lazy Sequences
Iterator methods compile into state machines. Exceptions surface during enumeration, not at the call.
Validate arguments eagerly: split into a public validating method plus a private iterator.
Async streams (IAsyncEnumerable(Of T)) can be consumed via GetAsyncEnumerator() / MoveNextAsync(), since VB has no Await For Each syntax.
Public Iterator Function Primes() As IEnumerable(Of Integer)
Dim n = 2
Do
If IsPrime(n) Then Yield n
n += 1
Loop
End Function
Public Iterator Function ReadRecords(path As String) As IEnumerable(Of String())
Using parser As New FileIO.TextFieldParser(path) With {.TextFieldType = FileIO.FieldType.Delimited}
parser.SetDelimiters(",")
While Not parser.EndOfData
Yield parser.ReadFields()
End While
End Using ' disposed when enumeration completes or stops early
End Function
Dim first10 = Primes().Take(10).ToList() ' lazy: computes only 10
Dim bigOrders = ReadRecords("orders.csv").Skip(1).Where(Function(f) CDec(f(3)) > 1000)