Tutorials Design Patterns in C#
Iterator Pattern — Complete Guide
Iterator Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 16 of 69
Iterator Pattern
GoF Core ✓ → Enterprise → Cloud & Craft
Enterprise · 2 — App patterns · ~6 min · Module 3: Behavioral Design Patterns
What is this?
Iterator walks a collection without exposing its internal structure — C# foreach/IEnumerable already implements this.
Why should you care?
ShopNest custom paginated catalog cursors should feel like foreach without leaking SQL details.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public sealed class SkuPage
{
private readonly string[] _skus;
public SkuPage(params string[] skus) => _skus = skus;
public IEnumerator<string> GetEnumerator()
{
foreach (var s in _skus) yield return s;
}
}
foreach (var sku in new SkuPage("HD-100", "HD-200"))
Console.WriteLine(sku);
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- yield return builds an iterator state machine.
- Callers foreach without knowing the array.
- Rarely build a manual IEnumerator unless you need special cursor semantics.
Practice next
- Foreach the SkuPage.
- Add a Filter iterator with yield.
- Prefer IAsyncEnumerable for streaming APIs.
- Yield only SKUs starting with HD.
- Write an async iterator reading pages.
Remember
Traverse without exposing guts. IEnumerable/yield in C#. Custom iterators for cursors.
ShopNest catalog cursor
API streams SKUs via IAsyncEnumerable.
Outcome: Clients iterate pages without SQL knowledge.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!