Iterators in C#

An iterator in C# performs custom iteration over a collection using the yield keyword. It returns elements one at a time and remembers its current position, making it memory-efficient for large datasets. Iterators implement lazy evaluation, meaning values are generated only when requested.

Syntax

Following is the syntax for creating an iterator method −

public static IEnumerable<T> MethodName() {
    // logic here
    yield return value;
    // more logic
    yield return anotherValue;
}

The yield break statement can be used to end the iteration early −

yield break;  // stops iteration

How Iterators Work

When you call an iterator method, it doesn't execute immediately. Instead, it returns an IEnumerable object. The actual execution happens when you iterate over the result using foreach or manually with GetEnumerator().

Iterator Execution Flow Method Called Returns IEnumerable foreach Started Execution begins yield return Pauses & returns current value Next Iteration Resumes execution

Basic Iterator Example

using System;
using System.Collections.Generic;

class Program {
    public static IEnumerable<string> GetNumbers() {
        int[] arr = new int[] {99, 45, 76};
        
        foreach (var val in arr) {
            yield return val.ToString();
        }
    }

    public static void Main(string[] args) {
        IEnumerable<string> numbers = GetNumbers();
        foreach (var element in numbers) {
            Console.WriteLine(element);
        }
    }
}

The output of the above code is −

99
45
76

Using yield break

using System;
using System.Collections.Generic;

class Program {
    public static IEnumerable<int> GetEvenNumbers(int max) {
        for (int i = 0; i <= max; i++) {
            if (i % 2 == 0) {
                yield return i;
            }
            if (i > 10) {
                yield break;  // Stop iteration early
            }
        }
    }

    public static void Main(string[] args) {
        foreach (var num in GetEvenNumbers(20)) {
            Console.WriteLine(num);
        }
    }
}

The output of the above code is −

0
2
4
6
8
10

Iterator with Complex Logic

using System;
using System.Collections.Generic;

class Program {
    public static IEnumerable<int> FibonacciSequence(int count) {
        int a = 0, b = 1;
        
        for (int i = 0; i < count; i++) {
            yield return a;
            int temp = a + b;
            a = b;
            b = temp;
        }
    }

    public static void Main(string[] args) {
        Console.WriteLine("First 8 Fibonacci numbers:");
        foreach (var fib in FibonacciSequence(8)) {
            Console.WriteLine(fib);
        }
    }
}

The output of the above code is −

First 8 Fibonacci numbers:
0
1
1
2
3
5
8
13

Key Benefits

  • Memory Efficiency − Values are generated on-demand, not stored in memory all at once.

  • Lazy Evaluation − Computation happens only when values are actually needed.

  • State Preservation − Iterator remembers where it left off between iterations.

  • Clean Code − Eliminates the need to implement IEnumerator manually.

Conclusion

Iterators in C# provide an elegant way to implement custom iteration logic using the yield keyword. They offer memory efficiency through lazy evaluation and automatically handle the complexity of implementing IEnumerable and IEnumerator interfaces.

Updated on: 2026-03-17T07:04:35+05:30

421 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements