Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need IEnumerator.Current in a class implementing IEnumerator<T>?

I have a class that implements IEnumerator<string>. See below:

public class MyClass : IEnumerator<string>
{
    public bool MoveNext()
    {
        //....
    }

    //Implement other required methods....

   //Confusion lies below:
   public string Current { get { return this.CurrentLine; } }

   //Why do I need to implement IEnumerator.Current?!  In my tests, it's not even called    during my iteration
   object IEnumerator.Current { get { throw new NotImplementedException(); } }

}   

Besides the fact that .Current property exists on both the IEnumerator<T> interface and the IEnumerator interface (which IEnumerator<T> inherits), what's the point of implementing it? As seen above it's not even called.

like image 239
contactmatt Avatar asked Mar 02 '11 18:03

contactmatt


People also ask

What does IEnumerator do c#?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

What is IEnumerator?

IEnumerator is an interface, which when implemented allows you to iterate through the list of controls. To implement it requires that you provide two methods - Reset to go back to the beginning of the list, and MoveNext to move forward, and Current to get the current item.

Is IEnumerator a return type?

To implement collection, I have to complete GeEnumerator(). But the return type of this function is IEnumerator.


2 Answers

IEnumerator<T> implements IEnumerator, so at the most basic level you have to fulfill the contract.

Specifically as to why - what happens if someone does this:

((IEnumerator)yourInstance).Current

They (usually) should expect to get a loosely-typed copy of the same value/reference returned from IEnumerator<T>'s implementation. So in most cases, just return this.Current and don't worry about it :)

(FYI - returning this.Current is also good practice because it follows DRY and SRP - let the strongly-typed version of Current deal with the implementation details of what Current actually is.)

like image 144
Rex M Avatar answered Nov 04 '22 14:11

Rex M


The reason is that IEnumerator<T> inherits IEnumerator so when you inherit from IEnumerator<T> you implicitly also inherit from IEnumerator. If you advertise an interface you should also provide an implementation for that interface even if you never intend to use it.

like image 21
Mark Byers Avatar answered Nov 04 '22 13:11

Mark Byers