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.
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.
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.
To implement collection, I have to complete GeEnumerator(). But the return type of this function is IEnumerator.
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.)
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.
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