When implementing IEnumerable & IEnumerator on a class I was writing during training, I noticed that I was required to specify two implementations for the property "Current".
public class PeopleEnumerator : IEnumerator<Person>
{
People people; // my collection I'm enumerating (just a wrapped array).
int index; // my index to keep track of where in the collection I am.
...
//implementation for Person
public Person Current { get { return people[index]; } }
//implementation for object
object Enumerator.Current { get { return people[index]; } }
}
I roughly understand that I'm implementing some non-generic version of IEnumerator and a "Current" property for it, however I don't understand the following things:
Thanks in advance!
Here is the documentation on IEnumerator . They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate , which means "to count off or name one by one".
IEnumerable interface should be implemented in order to use your custom objects in the form of a collection (series of values or objects). Which means you can use it directly with the foreach statement. IEnumerable interface has a method called GetEnumerator() which returns an object implemented IEnumerator.
An IEnumerator is a thing that can enumerate: it has the Current property and the MoveNext and Reset methods (which in . NET code you probably won't call explicitly, though you could). An IEnumerable is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator .
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. This works for readonly access to a collection that implements that IEnumerable can be used with a foreach statement. IEnumerator has two methods MoveNext and Reset. It also has a property called Current.
There's only one reason you must implement two different interfaces: backwards compatibility. C# 1.0 did not have generics.
In C# 2.0, we got IEnumerator<T>
which extends the 1.0 IEnumerator
.
- Why am I allowed to overload by return type here? Presumably it has something to do with the explicit IEnumerator.Current; however the reasons are opaque to me.
You cannot overload methods or properties by return type only; that's why one of them must be an explicit implementation.
- Why can "object IEnumerator.Current" not be specified as "public"?
Same reason. It has to be an explicit implementation. An explicit implementation cannot have a visibility modifier as a rule. It cannot possibly have any other visibility. IEnumerator.Current
can only be called through an instance of the IEnumerator
interface.
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