Reputation: 2518
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.
Upvotes: 9
Views: 2115
Reputation: 64487
They both can exist because one of them will be implemented explicitly:
IEnumerator IEnumerable.GetEnumerator()
{
}
If you attempt to make them both implicitly defined, you will get compile errors.
Yes, they should both return the same data.
You are required to define the two versions of GetEnumerator
in order to satisfy both interfaces (IEnumerable
and IEnumerable<T>
) from which IList<T>
is derived. In practice, however, you tend to find the non-generic version of GetEnumerator
just calls the generic one in most implementations.
Upvotes: 1
Reputation: 26638
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.
Upvotes: 13
Reputation: 13947
IEnumerator enumerates objects, whereas IEnumerator enumerates T. For your second question, the second function is fully qualified:
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
}
vs
public IEnumerator<T> GetEnumerator()
{
}
Upvotes: 0
Reputation: 25684
IList<T>
Implements both IEnumerable<T>
and IEnumerable
. The different implementations of GetEnumerator
come from each of these interfaces. Both should return the same data.
Upvotes: 0
Reputation: 33930
Yes, both methods should return the same data.
They can co-exist because they are part of two different interfaces, IEnumerable
and IEnumerable<T>
.
Upvotes: 4
Reputation: 245429
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.
Upvotes: 8