Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does implementing 'IList<T>' require defining two 'GetEnumerator' methods?

When I implement IList<T>, I find that I am required to define two GetEnumerator methods. One returns a value that is of type IEnumerator, while the other returns IEnumerator<T>.

I'm a little confused about the difference between these two GetEnumerator methods. While the return types are obviously different, don't they essentially hold the same data?

In addition, why is it that both versions of GetEnumerator can exist as methods when they differ only by return type? This seems to violate the rule in C# which specifies that overloaded methods cannot differ only by return type.

like image 332
MyNameIsJob Avatar asked Dec 10 '10 16:12

MyNameIsJob


People also ask

What is IList in C# with example?

In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.

What is GetEnumerator?

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

Does List implement IList?

IList is an interface. List is one concrete type that implements the IList interface.

Which interface represents a collection of objects that can be individually access by index?

IList Interface (System.


2 Answers

Both should return the same data, yes.

IEnumerator is from .Net v1.1, before generic typing was introduced. IEnumerator<T> is the generically typed version added in .Net v2.

The "old" version, IEnumerator, has been kept for compatibility, so now IList<T> implements both.

The difference between the two is that the non-generic IEnumerator returns object's whereas the generic IEnumerator<T> returns T's. Although, the c# compiler will insert a cast for you to make the non-generic IEnumerator seem strongly-typed when used in a foreach.

The presence of a generic type argument is enough for the compiler to differentiate between the two interfaces, but for a class to implement both one must be explicitly implemented.

like image 102
quentin-starin Avatar answered Oct 18 '22 09:10

quentin-starin


The two come from separate interfaces that IList itself implements, which is why you have to implement both:

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable

And they're both able to exist because of Explicit Interface Implementation.

like image 29
Justin Niessner Avatar answered Oct 18 '22 09:10

Justin Niessner