Reputation: 228
For example:
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
//This interface allows the caller to obtain a container's items.
public interface IEnumerator
{
bool MoveNext ();
object Current { get;}
void Reset();
}
Why not just implement IEnumerator instead of using IEnumerable that forces you to implement a method that returns type IEnumerator?
Upvotes: 4
Views: 220
Reputation: 26362
You can check the differences at this very nice article
TL;DR - Effectively, the IEnumerable
contract assumes that you have a way of maintaning the state of the Enumerable.
Similarities
Both of these interfaces help to loop through the collection.
Relation
The IEnumerable interface actually uses IEnumerator. The main reason to create an IEnumerable is to make the syntax shorter and simpler.
If you go to the definition of the IEnumerable interface, you will see this interface has a method GetEnumerator() that returns an IEnumerator object back.
Differences
The main difference between IEnumerable and IEnumerator is an IEnumerator retains its cursor's current state.
When to use:
So, if you want to loop sequentially through the collection, use an IEnumerable interface else if you want to retain the cursor position and want to pass it from one function to another function then use an IEnumerator interface.
Example:
static void iEnumeratorMethodOne(IEnumerator<string> i)
{
while(i.MoveNext())
{
Console.WriteLine(i.Current);
if(i.Current == "June")
{
iEnumeratorMethodTwo(i);
}
}
}
static void iEnumeratorMethodTwo(IEnumerator<string> i)
{
while(i.MoveNext())
{
Console.WriteLine(i.Current);
}
}
Upvotes: 2