← Back to C# Course | Chapter 8: Interfaces | Lesson 6 of 6

IEnumerable

In this page:

  1. IEnumerable

IEnumerable

IEnumerable<T> is the interface that makes a type usable in a foreach loop by exposing a way to get an enumerator over its elements. Arrays, List<T>, and Dictionary<K,V> all implement it. You can implement it yourself on a custom collection type using yield return to produce elements lazily.

Note: yield return inside a method returning IEnumerable<T> builds an iterator without manually implementing IEnumerator.

Example: IEnumerable

markup
using System;
using System.Collections;
using System.Collections.Generic;

class Countdown : IEnumerable<int>
{
    private int start;
    public Countdown(int start) { this.start = start; }

    public IEnumerator<int> GetEnumerator()
    {
        for (int i = start; i >= 0; i--)
        {
            yield return i;
        }
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

class Program
{
    static void Main(string[] args)
    {
        foreach (int n in new Countdown(3))
        {
            Console.WriteLine(n);
        }
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.