A design pattern question for enumerators.

  • Thread starter Thread starter Peter Rilling
  • Start date Start date
P

Peter Rilling

A design pattern question.

As you know, an enumerator in .NET is broken into two interface (IEnumerable
and IEnumerator). Is there a benefit in having two interfaces? Why not
just have the IEnumerator interface with the methods that interact with the
collection?
 
A design pattern question.

As you know, an enumerator in .NET is broken into two interface (IEnumerable
and IEnumerator). Is there a benefit in having two interfaces? Why not
just have the IEnumerator interface with the methods that interact with the
collection?

As I understand it...

Among other reasons, 2 or more callers may be doing enumerations of the
same enumerable at the same time, so they each need to have different
current items Something has to track the current item for each caller, and
that something is the enumerator.
 
I found that confusing at first too. However, now it makes sense. It
seperates interface from implementation. The IEnumerable method signature,
GetEnumerator(), could have been included in the IEnumerator interface,
however that would require your class implement all the other methods (i.e.
MoveNext) when all it really wanted to do was return an object of type
IEnumerator. For example, you could have a class that allows an object
(that implements IEnumerator) to be stored during construction or set in a
method/property. In that case, your class does not care about implementing
IEnumerator methods, it just needs to return an instance of an IEnumerator
when GetEnumerator() is called on its IEnumerable interface. It allows you
to have multiple Enumerators for your class without having to implement the
IEnumerator methods in your class.
 
Back
Top