0
0
CsharpConceptBeginner · 3 min read

What is IEnumerator in C#: Simple Explanation and Example

IEnumerator in C# is an interface that allows you to move through a collection one item at a time. It provides simple methods to access each element sequentially without exposing the collection's internal structure.
⚙️

How It Works

Think of IEnumerator as a bookmark that helps you read through a book page by page. Instead of jumping around, you move forward one page at a time. In programming, this means you can look at each item in a list or collection one after another.

The interface has two main parts: a method to move to the next item and a property to get the current item. When you start, the bookmark is before the first item, so you call the method to move it forward. If there is an item, you can read it; if not, you know you've reached the end.

This way, IEnumerator hides the details of how the collection stores items and just lets you focus on visiting each item in order.

💻

Example

This example shows how to use IEnumerator to loop through a list of colors and print each one.

csharp
using System;
using System.Collections;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> colors = new List<string> { "Red", "Green", "Blue" };
        IEnumerator<string> enumerator = colors.GetEnumerator();

        while (enumerator.MoveNext())
        {
            string color = enumerator.Current;
            Console.WriteLine(color);
        }
    }
}
Output
Red Green Blue
🎯

When to Use

Use IEnumerator when you want to look at each item in a collection one by one without changing the collection. It is helpful when you need to process items in order, like reading a list of names or numbers.

For example, if you have a list of tasks and want to check each task's status, IEnumerator lets you do this simply and safely. It is also used behind the scenes in foreach loops, so understanding it helps you know how those loops work.

Key Points

  • IEnumerator lets you move through a collection one item at a time.
  • It has MoveNext() to advance and Current to get the current item.
  • It hides how the collection stores items, focusing on sequential access.
  • foreach loops use IEnumerator internally.

Key Takeaways

IEnumerator allows sequential access to collection items without exposing internal details.
Use MoveNext() to advance and Current to read the current item.
IEnumerator is the foundation for foreach loops in C#.
It is useful when you want to process items one by one safely and simply.