Working on implementing the IEnumerable interface.
I actually found two methods that need to be implemented:
public IEnumerator<Item> GetEnumerator()
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
Not sure why I need to implement these two methods (which look quite similar). Could anyone explain it to me?
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
GetEnumerator Method is used to returns an enumerator that iterates through the List<T>. Syntax: public System.
IEnumerator is the base interface for all non-generic enumerators. Its generic equivalent is the System. Collections.
IEnumerable<T> extends IEnumerable, so you need to provide both a generic and non-generic version of the method.
A common solution is to have the non-generic solution simply call the generic solution, since IEnumerator<T> also extends IEnumerator.
Part of the answer is "for historical reasons".
The IEnumerable interface has been around since .NET 1.1, whereas generics (and thus IEnumerable<T>) were added in .NET 2. IEnumerable<T> extends IEnumerable, which was a sensible decision because it allows you to use an IEnumerable<T> in code that was already written to take an IEnumerable.
But that means that to implement IEnumerable<T> (which includes the IEnumerator<T> GetEnumerator() method) you also have to implement IEnumerable (which includes the IEnumerator GetEnumerator() method).
As Servy noted, it's not that big a deal, because you can just do this:
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
where the non-explicit implementation GetEnumerator is the one whose return type is IEnumerator<T>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With