0
0
CsharpConceptBeginner · 3 min read

What is IEnumerable in C#: Simple Explanation and Example

IEnumerable in C# is an interface that allows you to loop through a collection of items one by one. It provides a simple way to access elements sequentially without exposing the collection’s internal structure.
⚙️

How It Works

Think of IEnumerable as a way to read a book page by page without seeing the whole book at once. It lets you move through a list or collection step by step, like flipping pages, so you can look at each item in order.

Under the hood, IEnumerable provides a method called GetEnumerator() that returns an enumerator. This enumerator keeps track of your current position in the collection and moves forward when you ask for the next item. This way, you don’t need to know how the collection stores its data, just how to get each item one after another.

đź’»

Example

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

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        IEnumerable<int> numbers = new List<int> { 10, 20, 30, 40 };

        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}
Output
10 20 30 40
🎯

When to Use

Use IEnumerable when you want to read or loop through a collection without changing it. It is perfect for situations where you only need to look at items one by one, like reading a list of names, processing data streams, or working with any collection where you don’t need to add or remove items.

It is also useful when you want to write methods that can work with any collection type, such as arrays, lists, or custom collections, because IEnumerable works with all of them.

âś…

Key Points

  • IEnumerable allows simple, forward-only access to a collection.
  • It hides the collection’s internal structure.
  • It supports foreach loops in C#.
  • It is read-only and does not allow modifying the collection.
  • Works with many collection types like arrays, lists, and more.
âś…

Key Takeaways

IEnumerable lets you loop through collections easily and safely.
It provides a way to access items one by one without exposing internal details.
Use it when you only need to read or iterate over data, not modify it.
It works with many collection types, making your code flexible.
Supports foreach loops for clean and simple iteration.