Complete C# Tutorial

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 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! πŸ”₯πŸš€

Leave a Comment

Share this Doc

Iterators

Or copy link