Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must IEnumerator<T> GetEnumerator() and GetEnumerator() be implemented?

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?

like image 220
Jason Avatar asked Dec 20 '13 19:12

Jason


People also ask

What is the use of IEnumerator?

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.

What is GetEnumerator?

GetEnumerator Method is used to returns an enumerator that iterates through the List<T>. Syntax: public System.

Is IEnumerator an interface?

IEnumerator is the base interface for all non-generic enumerators. Its generic equivalent is the System. Collections.


2 Answers

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.

like image 179
Servy Avatar answered Sep 27 '22 22:09

Servy


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

like image 25
Tim Goodman Avatar answered Sep 27 '22 22:09

Tim Goodman