tags:

views:

242

answers:

1

Consider two iterator methods with the same bodies:

public static IEnumerable<int> It1() { 
    ...
}

public static IEnumerator<int> It2() { 
    ...
}

Is there any circumstance where calling It2 is different from calling It1.GetEnumerator()?

Is there ever a good reason to define an iterator as IEnumerator<T> over IEnumerable<T>? The only one I can think of is when you are implementing IEnumerable<T>.GetEnumerator().

EDIT: By iterator methods I mean methods using yield return and yield break constructs.

+7  A: 

As noted, you can't foreach over an IEnumerator<T>. Because of that, it makes it difficult to integrate into places in code where you want to iterate over what you are returning.

Also, the imporance here is that IEnumerable<T> is meant to be a factory, so that you can produce implementations of IEnumerator<T> that aren't directly tied to the implementation of the collection of T.

Even more important now is the fact that all the extension methods for LINQ work off IEnumerable<T>, so you will want to make your enumerations as easy to work with as possible by returning that.

casperOne
Yes, that's all good reasons to prefer IEnumerable<T> over IEnumerator<T>. That's why I asked about the opposite direction.
Alexey Romanov