Why do arrays in .net only implement IEnumerable and not IEnumerable?

Arrays do implement IEnumerable<T>, but it is done as part of the special knowledge the CLI has for arrays. This works as if it were an explicit implementation (but isn’t: it is done at runtime). Many tools will not show this implementation, this is described in the Remarks section of the Array class overview. You … Read more

Return an empty IEnumerator

This is simple in C# 2: public IEnumerator GetEnumerator() { yield break; } You need the yield break statement to force the compiler to treat it as an iterator block. This will be less efficient than a “custom” empty iterator, but it’s simpler code…

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

Simple IEnumerator use (with example)

Here is the documentation on IEnumerator. They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate, which means “to count off or name one by one”. IEnumerator and IEnumerator<T> is provided by all IEnumerable and IEnumerable<T> … 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