Question

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?

Was it helpful?

Solution 2

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>.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top