Why does IEnumerator inherit from IDisposable while the non-generic IEnumerator does not?

Basically it was an oversight. In C# 1.0, foreach never called Dispose 1. With C# 1.2 (introduced in VS2003 – there’s no 1.1, bizarrely) foreach began to check in the finally block whether or not the iterator implemented IDisposable – they had to do it that way, because retrospectively making IEnumerator extend IDisposable would have … Read more

What is the difference between IEnumerator and IEnumerable? [duplicate]

IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface, this in turn allows readonly access to a collection. A collection that implements IEnumerable can be used with a foreach statement. Definition IEnumerable public IEnumerator GetEnumerator(); IEnumerator public object Current; public void Reset(); public bool MoveNext(); example code from codebetter.com

Can anyone explain IEnumerable and IEnumerator to me? [closed]

for example, when to use it over foreach? You don’t use IEnumerable “over” foreach. Implementing IEnumerable makes using foreach possible. When you write code like: foreach (Foo bar in baz) { … } it’s functionally equivalent to writing: IEnumerator bat = baz.GetEnumerator(); while (bat.MoveNext()) { bar = (Foo)bat.Current … } By “functionally equivalent,” I mean … Read more