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.
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.
GetEnumerator Method is used to returns an enumerator that iterates through the List<T>. Syntax: public System.
IList is an interface. List is one concrete type that implements the IList interface.
IList Interface (System.
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.
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.
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