IEnumerable with custom Enumerator
suggest changeImplementing 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:
- Using ranges of numbers based on a function rather than a collection of objects
- Implementing different iteration algorithms over collections, like DFS or BFS on a graph collection
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);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents