IEnumerable with custom Enumerator

suggest change

Implementing IEnumerable lets a class be enumerated in the same way as a BCL collection. The class returns an IEnumerator that tracks the position. It does not subclass a framework type named Enumerator.

Besides iterating over a stored collection, examples include:

public class CoffeeCollection : IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        return new CoffeeEnumerator();
    }

    public class CoffeeEnumerator : IEnumerator
    {
        string[] beverages = new string[3] { "espresso", "macchiato", "latte" };
        int currentIndex = -1;

        public object Current
        {
            get
            {
                if (currentIndex < 0 || currentIndex >= beverages.Length)
                    throw new InvalidOperationException();
                return beverages[currentIndex];
            }
        }

        public bool MoveNext()
        {
            currentIndex++;
            return currentIndex < beverages.Length;
        }

        public void Reset()
        {
            currentIndex = -1;
        }
    }
}

        foreach (var coffee in new CoffeeCollection())
            Console.WriteLine(coffee);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents