0
0
CsharpConceptBeginner · 3 min read

What is Iterator in C#: Explanation and Example

In C#, an iterator is a method or property that uses yield return to provide a way to loop through a collection one item at a time without creating an entire collection in memory. It simplifies creating custom sequences that can be enumerated with foreach.
⚙️

How It Works

Think of an iterator like a bookmark in a book. Instead of reading the whole book at once, you read one page, then save your place, and come back later to read the next page. In C#, an iterator lets you do this with data: it returns one item at a time and remembers where it left off.

Under the hood, when you use yield return inside a method, C# creates a special object that keeps track of the current position in the sequence. Each time you ask for the next item, it continues from where it stopped, making it efficient because it doesn't need to store all items at once.

💻

Example

This example shows a simple iterator method that returns numbers from 1 to 5 one by one using yield return. You can use it in a foreach loop to get each number.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static IEnumerable<int> GetNumbers()
    {
        for (int i = 1; i <= 5; i++)
        {
            yield return i;
        }
    }

    static void Main()
    {
        foreach (int number in GetNumbers())
        {
            Console.WriteLine(number);
        }
    }
}
Output
1 2 3 4 5
🎯

When to Use

Use iterators when you want to create a sequence of values that are generated on the fly, especially if the full list is large or expensive to create all at once. For example, reading lines from a large file, generating infinite sequences, or filtering data without copying it all.

Iterators help save memory and improve performance by producing items only as needed, making your programs more efficient and easier to read.

Key Points

  • An iterator uses yield return to return items one at a time.
  • It allows looping over data without creating a full collection in memory.
  • Iterators simplify code for generating sequences or filtering data.
  • They work well with foreach loops for easy reading.

Key Takeaways

An iterator in C# returns items one by one using yield return.
It helps save memory by not storing all items at once.
Use iterators to create efficient, easy-to-read sequences.
Iterators work seamlessly with foreach loops.
They are useful for large or infinite data sequences.