IEnumerable<T> provides two GetEnumerator methods - what is the difference between them?
Asked Answered
M

5

11

When I emplement IEnumerable<T> interface I see two GetEnumerator methods: one returning IEnumerator and other IEnumerator<T>. When would I use one or another?

Margret answered 18/2, 2009 at 11:27 Comment(0)
H
8

If you are implementing the IEnumerable<T> generic interface, you will pretty much always have to use the generic GetEnumerator method - unless you cast your object explicitly to (non-generic) IEnumerable.

The reason is backwards compatability with .NET 1.0/1.1 which didn't support generics.

Hipped answered 18/2, 2009 at 11:33 Comment(0)
B
35

You usually implement both. One is the newer, generic version that returns a typesafe enumerator (IEnumerator<T>). The other one is for compatibility with Legacy code (returns IEnumerator). A typical implementation is:

public IEnumerator<T> GetEnumerator() {
    foreach(T item in items) {
        yield return item;
    }
}

IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator();
}
Boggart answered 18/2, 2009 at 11:33 Comment(2)
this one helped me a lot, avoiding the extra-class for the nested enumerator!Doggery
+1. I also was googling to find a reference implementation that avoids the nested enumerator class and this was the first answer I came to.Apsis
B
13

The reason there are two methods is because IEnumerable<T> inherits the IEnumerable interface so you are seeing the generic method from IEnumerable<T> and the non-generic method from IEnumerable.

Here is how you want to implement the interface in your type:

class Foo : IEnumerable<Foo>
{
    public IEnumerator<Foo> GetEnumerator()   
    {
        // do your thing here
    }

    // do a EIMI here and simply call the generic method
    IEnumerator IEnumerable.GetEnumerator()
    {
        this.GetEnumerator();
    }
}
Bang answered 18/2, 2009 at 11:33 Comment(2)
+1 - EIMI = Explicit interface member implementationNicotiana
But how on earth Foo : IEnumerable<Foo> makes sense?Curable
H
8

If you are implementing the IEnumerable<T> generic interface, you will pretty much always have to use the generic GetEnumerator method - unless you cast your object explicitly to (non-generic) IEnumerable.

The reason is backwards compatability with .NET 1.0/1.1 which didn't support generics.

Hipped answered 18/2, 2009 at 11:33 Comment(0)
T
4

Usually GetEnumerator() calls GetEnumerator<T>(), so there should not be much difference in behavior. As for why there are two methods, this is done for backwards compatibility and for use in situation where T is not of great interest (or is just unknown).

Tensive answered 18/2, 2009 at 11:32 Comment(0)
M
2

The one is generic, the other one not. I believe the compiler prefers to use the generic overload.

Muzhik answered 18/2, 2009 at 11:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.