What is Iterator in C#: Explanation and Example
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.
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); } } }
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 returnto 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
foreachloops for easy reading.