Iterators in C# using the yield keyword

 
Consider the following example.

private string[] GetCityNames()
       {
           string[] str = { "Paris", "Londan", "New Delhi", "New York", "Tokyo" };
           string[] Cityname = new string[5];
           for (int i = 0; i < str.Length - 1; i++)
           {
               Cityname[i] = (str[i] + "City");
            }
           return Cityname;
       }
  private void main()
       {
           foreach (string strCity in GetCityNames())
           {
               System.Console.Write(strCity + " ");
           }
       }

 
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(). Ok i explain consider the above example, System.Console.Write(strCity + ” “); statment will be execute after finish GetCityNames() function and with the help of Yield keyword we can execute this line just after add a one city in GetCityNames() function. We can do it by using the Yield keyword.
Now see the following code, output will be same as above example.
 

   private System.Collections.IEnumerable GetCityNames()
       {
           string[] str = { "Paris", "Londan", "New Delhi", "New York", "Tokyo" };
           string[] Cityname = new string[5];
           for (int i = 0; i < str.Length - 1; i++)
           {
               Cityname[i] = (str[i] + "City");
               yield return Cityname[i];
           }
       }
   private void main()
       {
           foreach (string strCity in GetCityNames())
           {
               System.Console.Write(strCity + " ");
           }
       }

 
As you can see, 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.
 
Learn about: Using Yield and Iterator in Visual Basic 2012
 
Note: The return type of an iterator must be IEnumerable, IEnumerator, IEnumerable, or IEnumerator. for example: we can not use yield in array type function if we use the yield in the array type function you will see an error like ..cannot be an iterator block because ‘string[]‘ is not an iterator interface type.
you can write more reliable code with the help of yield command.