A C# iterator is a function that helps in traversing through items in a collection, array, or list. It employs the yield return statement to provide elements one by one during iteration.
The iterator stores the present position and in the following iteration, it provides the subsequent element.
The output type of an iterator may be either IEnumerable<T> or IEnumerator<T>.
To halt the iteration process, we can utilize the yield break statement.
C# Iterator Example 1
In this example, we are iterating array elements.
using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharpFeatures
{
class IteratorExample
{
public static IEnumerable<string> GetArray()
{
int[] arr = new int[] { 5,8,6,9,1 };
// Iterating array elements and returning
foreach (var element in arr)
{
yield return element.ToString(); // It returns elements after executing each iteration
}
}
public static void Main(string[] args)
{
// Storing elements, returned from the iterator method GetArray()
IEnumerable<string> elements = GetArray();
foreach (var element in elements) // Iterating returned elements
{
Console.WriteLine(element);
}
}
}
}
Output:
5
8
6
9
1
Iterator can be utilized to traverse through elements in a collection. In this specific instance, we are iterating over elements in a list.
C# Iterator Example 2
using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharpFeatures
{
class IteratorExample
{
public static IEnumerable<string> GetList()
{
// List of string elements
List<string> list = new List<string>();
list.Add("Rohan"); // Adding elements
list.Add("Peter");
list.Add("Irfan");
list.Add("Sohan");
// Iterating and returing list elements
foreach (var element in list)
{
yield return element; // It returns elements after executing each iteration
}
}
public static void Main(string[] args)
{
// Storing elements, returned from the iterator method GetList()
IEnumerable<string> elements = GetList();
foreach (var element in elements) // Iterating returned elements
{
Console.WriteLine(element);
}
}
}
}
Output:
Rohan
Peter
Irfan
Sohan