Iterator Functions in C#


An iterator method performs a custom iteration over a collection. It uses the yield return statement and returns each element one at a time. The iterator remembers the current location and in the next iteration the next element is returned.

The following is an example −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo {
   class Program {
      public static IEnumerable display() {
         int[] arr = new int[] {99,45,76};

         foreach (var val in arr) {
            yield return val.ToString();
         }
      }

      public static void Main(string[] args) {
         IEnumerable ele = display();
         foreach (var element in ele) {
            Console.WriteLine(element);
         }  
      }
   }
}

Output

99
45
76

Above, we have an iterator method display() that use the yield statement to return one element at a time −

public static IEnumerable display() {
   int[] arr = new int[] {99,45,76};

   foreach (var val in arr) {
      yield return val.ToString();
   }
}

The result is stored and each element is iterated and printed −

IEnumerable ele = display();
foreach (var element in ele) {
   Console.WriteLine(element);
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements