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! 🔥🚀
