0Pricing
C# Academy · Lesson

Custom Enumerables

Implement IEnumerable with iterators.

Building Your Own Enumerable

By implementing IEnumerable<T> on a class, you make it usable in a foreach. Combined with iterator methods, this lets you create custom collections and ranges with very little code.

Implementing GetEnumerator With yield

The simplest way to implement IEnumerable<T> is to write GetEnumerator as an iterator using yield return. The compiler builds the enumerator for you.

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

public class IntRange : IEnumerable<int>
{
    private readonly int _start, _count;
    public IntRange(int start, int count) { _start = start; _count = count; }

    public IEnumerator<int> GetEnumerator()
    {
        for (int i = 0; i < _count; i++)
            yield return _start + i;
    }
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

public class Program
{
    public static void Main()
    {
        foreach (var n in new IntRange(5, 4))
            Console.WriteLine(n);
    }
}

All lessons in this course

  1. Iterator Methods with yield return
  2. yield break and Early Termination
  3. Lazy Evaluation Semantics
  4. Custom Enumerables
← Back to C# Academy