IEnumerable vs IEnumerator

  • Thread starter Thread starter Raj
  • Start date Start date
R

Raj

Why do we need to implment both IEnumerable and IEnumerator inorder to make
custom collection that can use foreach?

In what way these two are related or why do we need these interfaces instead
of one?

Thank you

Regards
Raj
 
Raj said:
Why do we need to implment both IEnumerable and IEnumerator inorder to make
custom collection that can use foreach?

You have to implement IEnumerable, because that's what the "foreach"
statement takes.

You have to implement IEnumerator, because otherwise what would your
IEnumerable.GetEnumerator() implementation return?

Of course, C# makes it very easy to implement IEnumerator. Doing so
isn't usually much of a problem.
In what way these two are related or why do we need these interfaces instead
of one?

There are lots of potential benefits to the design. However it seems to
me that one of the most obvious is that separating the two not only
provides a more realistic view of the implementor – that is, a
collection class itself isn't an enumerator, but rather something that
can be enumerated – but also that keeping the two interfaces separate
means you can easily have multiple enumerators operating simultaneously
without any special difficulty.

A given data object can be enumerable, and thus implements IEnumerable.
But you may have multiple sections of code all wanting to enumerate
that object at the same time, and encapsulating that logic in a separate
enumerator provides a simple, clean way to isolate those active
enumerations.

The alternative would be to have a single enumerator instance (i.e. the
class itself) that has to keep track of all active enumerations somehow.
Not only would this involve a lot more code and complexity, it would
make it a lot harder to know when it's safe to just abandon an
enumerator. The most obvious implementation for such a design would
wind up just recreating the enumerator idea, and having some
non-standard way of connecting the enumerator to the client through
whatever the enumerable interface wound up being.

Instead, .NET simply acknowledges that as the superior design and "bakes
it in" to the framework and language.

Pete
 
Raj said:
Why do we need to implment both IEnumerable and IEnumerator inorder to make
custom collection that can use foreach?

In what way these two are related or why do we need these interfaces instead
of one?

Thank you

Regards
Raj

Hi Raj,

I'll try to explain how it all works and the relationship to each other.

Say you have a deck of cards (your Array[]). The IEnumerable is the
Pointer that represents the position of a card in the deck of cards.
The IEnumerator moves to the pointer (ie. MoveNext(), Current(),
Reset()) to point to a card in the deck. So, (I'm guessing) the foreach
uses the MoveNext() to move the pointer through each card in the deck
from beginning until it reaches the end.

Mark Rogers
 
Back
Top