Open In App

Iterators in C#

Improve
Improve
Like Article
Like
Save
Share
Report

An iterator is a method in C# which is used in an array or in collections like the list, etc. to retrieve elements one by one. Or in other words, we can say that an iterator is used to perform an iteration over the collections. This feature is introduced in C# 2.0. It uses the yield return statement to return the element from the collection at a time and it always remembers the current location of the iterator, so when the next iteration takes place it will return the next element of the given collection. If you want to stop the iteration you will use the yield break statement. 

The return type of this method is IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>. Which means by using iterator compiler will automatically create IEnumerable or IEnumerator interface for you there is no need to implement IEnumerable or IEnumerator interface in your class for using a foreach loop. When the compiler identifies an iterator in your class it will automatically create the current, MoveNext and dispose of the method of IEnumerable or IEnumerator interface.

Important Points: 

  • Iterator can be used as a method, or as a property.
  • Iterator method is also known as get accessor.
  • You can use iterator as a method or get accessor.
  • You cannot use iterator in an events instance constructor, static constructor, or static finalizer.
  • An iterator method does not contain ref, or out parameters.
  • Here, yield is not reserved word, but when you use yield with return or break statement, then yield have special meaning.
  • You are allowed to use multiple yield statements.
  • It is generally used with generic or non-generic collections.
  • When you are working with iterator it is necessary to add System.Collections.Generic namespace in your program.

Example 1:

C#




// C# program to illustrate the concept
// of iterator using list collection
using System;
using System.Collections.Generic;
 
 class GFG {
 
    public static IEnumerable<string> GetMyList()
    {
        // Creating and adding elements in list
        List<string> my_list = new List<string>() {
                     "Cat", "Goat", "Dog", "Cow" };
 
        
        // Iterating the elements of my_list
        foreach(var items in my_list)
        {
            // Returning the element after every iteration
            yield return items;
        }
    }
 
    // Main Method
    static public void Main()
    {
 
        // Storing the elements of GetMyList
        IEnumerable<string> my_slist = GetMyList();
 
        // Display the elements return from iteration
        foreach(var i in my_slist)
        {
            Console.WriteLine(i);
        }
    }
}


Output: 

Cat
Goat
Dog
Cow

 

Example 2:

C#




// C# program to illustrate the concept
// of iterator using array
using System;
using System.Collections.Generic;
 
class GFG {
 
    public static IEnumerable<string> GetMyArray()
    {
        string[] myarray = new string[] {"Geeks",
                        "geeks123", "1234geeks"};
 
        // Iterating the elements of myarray
        foreach(var items in myarray)
        {
 
            // Returning the element after every iteration
            yield return items.ToString();
        }
    }
 
    // Main Method
    static public void Main()
    {
 
        // Storing the elements of GetMyArray
        IEnumerable<string> myitems = GetMyArray();
 
        // Display the elements return from iteration
        foreach(var i in myitems)
        {
            Console.WriteLine(i);
        }
    }
}


Output: 

Geeks
geeks123
1234geeks

 



Last Updated : 04 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments