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