In the framework classes of collections I have often seen IEnumerator<T>
separately implemented as an inner class and an instance of it is returned in the GetEnumerator
method.
Now suppose I'm writing my own collection classes which will have an inbuilt collection like List<T>
or T[]
act as the holder internally, say like this:
public class SpecialCollection<T> : IEnumerable<T>
{
List<T> list;
public SpecialCollection<T>()
{
}
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
//or
return list.Where(x => some logic).GetEnumerator();
//or directly rely on yield keyword
yield return x; //etc
}
}
Should I be writing my own enumerator class, or is it ok to return enumerator of the List<T>
class? Is there any circumstance under which should I be writing my own enumerator class?
I have a related question as well. If it's not all that important or doesn't make much of a difference, why do every collection class in the BCL write their own IEnumerator
?
For eg, List<T>
class has something like
T[] items;
public IEnumerator<T> GetEnumerator()
{
return new List<T>.Enumerator(items);
}