Why does the implementation of IList <T> require the definition of two GetEnumerator methods?

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

I am a little confused by the difference between the two GetEnumerator methods. Although the return types are obviously different, do they not essentially contain the same data?

Also, why can both versions of GetEnumerator exist as methods when they differ only in the return type? This seems to violate a rule in C #, which indicates that overloaded methods cannot differ only in the return type.

+6
list c # interface
source share
6 answers

Both should return the same data, yes.

IEnumerator - from .Net v1.1 before typical typing was introduced. IEnumerator<T> is a typically typed version added in .Net v2.

The "old" version of IEnumerator been retained for compatibility, so IList<T> implements both.

The difference between the two is that the non-generic IEnumerator returns an object, while the generic IEnumerator<T> returns T. Although, the C # compiler will insert cast for you to make the non-standard IEnumerator exponent strongly typed when used in foreach.

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

+8
source share

Both come from separate interfaces that IList itself implements, so you must implement both:

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

And both of them may exist due to the explicit implementation of the interface .

+7
source share

Yes, both methods must return the same data.

They can coexist because they are part of two different interfaces, IEnumerable and IEnumerable<T> .

+3
source share

Both of them can exist, because one of them will be implemented explicitly :

 IEnumerator IEnumerable.GetEnumerator() { } 

If you try to make them implicitly defined, you will get compilation errors.

Yes, they must return the same data.

You need to define two versions of GetEnumerator in order to satisfy both interfaces ( IEnumerable and IEnumerable<T> ), from which IList<T> is derived. In practice, however, you usually find that the non-standard version of GetEnumerator simply invokes the generic version in most implementations.

+1
source share

IList<T> Implements both IEnumerable<T> and IEnumerable . Different implementations of GetEnumerator come from each of these interfaces. Both must return the same data.

0
source share

IEnumerator lists objects, while IEnumerator lists T. For your second question, the second function is exactly the same:

  System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } 

against

 public IEnumerator<T> GetEnumerator() { } 
0
source share

All Articles