Iterators in Visual Basic 11

 
An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the Yield (Visual Basic) or yield return statement in c# to return each element one at a time. When a Yield or yield return statement is reached, the current location in code is remembered. Execution is restarted from that location the next time the iterator function is called.

Consider the following example.

Private Function GetCityNames() As String()
	Dim str As String() = {"Paris", "Londan", "New Delhi", "New York", "Tokyo"}
	Dim Cityname As String() = New String(4) {}
	For i As Integer = 0 To str.Length - 2
		Cityname(i) = (str(i) & "City")
	Next
	Return Cityname
End Function
Private Sub main()
	For Each strCity As String In GetCityNames()
		System.Console.Write(strCity & " ")
	Next
End Sub

 
In the above example calling procedure in main method start after GetCityNames() is finished by creating a list array of the city names. It would be great that the For Each in Main() already can start processing the first city which is retrieved in GetCityNames(). We can do it by using the Yield and Iterator keyword.
Now see the following code, output will be same as above example.
 

    Private Iterator Function GetCityNames() As System.Collections.IEnumerable
        Dim str As String() = {"Paris", "Londan", "New Delhi", "New York", "Tokyo"}
        For i As Integer = 0 To str.Length - 2
           yield  Return str(i) & "City"
        Next
    End Function
    Private Sub main()
        For Each strCity As String In GetCityNames()
            System.Console.Write(strCity & " ")
        Next
    End Sub

 
As you can see, we declare an GetCityNames() function with the keyword Iterator. we are using yield command in the GetCityNames() function. After each Yield command, the calling procedure(for each in main method) can already start processing the city name means in for each statement, city name will be start write just after the retrieving first city in the GetCityNames() function.
 

you can write more reliable code with the help of yield command.