C# › Indexers & Operator Overloading

How would you use an indexer together with a custom enumerator (implementing IEnumerable) to build a fully iterable, indexable custom collection class?

Advanced

Answer

Combine an indexer (for direct positional access via []) with an implementation of IEnumerable<T> (via GetEnumerator(), often using 'yield return') to give your custom collection BOTH capabilities simultaneously — letting consumers use foreach AND direct index access naturally, just like a built-in List<T>.
public class CircularBuffer<T> : IEnumerable<T> {
  private readonly T[] _items;
  public T this[int index] => _items[index % _items.Length]; // wraps around
  public CircularBuffer(int size) { _items = new T[size]; }
  public IEnumerator<T> GetEnumerator() {
    foreach (var item in _items) yield return item;
  }
  IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
Real-world example Building a custom circular buffer, sparse array, or specialized collection supporting both foreach iteration and direct indexed access.

Common follow-ups: What's the difference between implementing the generic IEnumerable<T> versus only the non-generic IEnumerable?