CodeBlanks Logo Icon CodeBlanks

IEnumerable<T>

C# course · Intermediate · Lesson 82/116

Learn the iterable collection contract with IEnumerable<T>.

The IEnumerable<T> contract

IEnumerable<T> is the contract for any sequence you can walk with foreach. It requires a single member: the GetEnumerator() method, which returns an IEnumerator<T>.

List<T>, T[] and Queue<T> all implement IEnumerable<T>. A method accepting IEnumerable<int> takes any of them. This makes swapping collections easy.

GetEnumerator and foreach

When you write foreach (var x in seq) the compiler calls seq.GetEnumerator() behind the scenes. The loop calls MoveNext() each step and reads the Current property. When MoveNext returns false the loop stops.

So foreach is a shortcut for explicitly calling IEnumerator members. A class implementing IEnumerable<T> works with foreach automatically, no extra code needed.

Exercise Write an IEnumerable<int> method

Write a PrintAll(IEnumerable<int> items) method that prints each item with foreach and Console.WriteLine. Add a PrintAll(list) call in Main.

Show example solution
In PrintAll iterate items with foreach, print each with WriteLine. Add PrintAll(list); in Main.
Example solution:
using System;
using System.Collections.Generic;

class Program
{
    static void PrintAll(IEnumerable<int> items)
    {
        foreach (var item in items)
        {
            Console.WriteLine(item);
        }
    }

    static void Main()
    {
        var list = new List<int> { 1, 2, 3 };
        PrintAll(list);
    }
}

Test yourself

  1. What does IEnumerable<T> provide?

    • foreach iteration
    • Indexed access
    • Thread safety
    • Automatic sorting
    Show answer

    foreach iteration — Correct. Types implementing IEnumerable<T> can be iterated with foreach.

  2. Implement the interface

    class Bag : IEnumerable<____>
    Show answer
    class Bag : IEnumerable<int>
  3. Match the member to its role

    GetEnumerator
    Returns iterator
    MoveNext
    Advances to next
    Current
    Current item
    Reset
    Returns to start

All lessons in Intermediate