C# Iterators Tutorial β Learn Iterators with a Simple Example
Real-World Example: A Candy Dispenser π¬
Imagine you have a candy dispenser filled with chocolates. πΊπ«
- When you press the button, it releases one candy at a time.
- You donβt get all the candies at once; you get them one by one as you keep pressing the button.
π‘ This is exactly how an iterator works in C#! It gives you one item at a time instead of dumping everything at once.
What You Are Going to Learn in This Lesson?
βοΈ What are iterators in C#?
βοΈ Why do we use them?
βοΈ A super simple real-world example to make it fun!
βοΈ A beginner-friendly Iterators Example C# with output.
βοΈ How iterators make looping easier.
What Are Iterators in C#?
An iterator is a way to loop through a collection one item at a time without exposing the whole list.
Instead of getting everything at once, we get each item only when needed.
Simple Iterators Example in C#
Letβs create a CandyDispenser that releases one candy at a time using an iterator!
Step 1: Create a Simple Iterator Class
using System;
using System.Collections;
using System.Collections.Generic;
class CandyDispenser
{
private string[] candies = { "Chocolate π«", "Lollipop π", "Gummy Bear π§Έ", "Mint π¬" };
public IEnumerable<string> GetCandies()
{
foreach (var candy in candies)
{
yield return candy; // Gives one candy at a time
}
}
}
Hereβs whatβs happening:
βοΈ We have an array of candies.
βοΈ Instead of giving all candies at once, the yield return
statement gives one candy at a time.
Step 2: Use the Iterator in Main Method
class Program
{
static void Main()
{
CandyDispenser dispenser = new CandyDispenser();
Console.WriteLine("π¬ Getting Candies from the Dispenser:");
foreach (var candy in dispenser.GetCandies())
{
Console.WriteLine("π " + candy);
}
}
}
Output:
π¬ Getting Candies from the Dispenser:
π Chocolate π«
π Lollipop π
π Gummy Bear π§Έ
π Mint π¬
How Does This Work?
βοΈ GetCandies()
doesn’t return all candies at once.
βοΈ Instead, yield return
returns one candy at a time when the foreach
loop asks for it.
βοΈ This makes the code more memory-efficient and flexible.
Why Should You Use Iterators?
π’ Use iterators when:
β
You want to process large collections one item at a time.
β
You donβt need all items at once (saves memory).
β
You want clean and efficient looping.
π΄ Donβt use iterators when:
β You need random access (iterators work sequentially).
β You want all data immediately.
Conclusion
So, we learned that iterators are like a candy dispenser! π¬ They give one item at a time instead of dumping everything at once. This makes looping simple, smart, and efficient. π
If you have difficulty or questions, drop a comment. We will be happy to help you. π
Next What?
In the next lesson, youβll learn about the yield
keyword in C#! Want to know how iterators work internally? Or how to create custom data streams? Thatβs exactly what weβll explore next! Stay tuned and keep coding! π₯π