I've been reading lately articles and documentation about deferred execution, LINQ, querying in general etc. and the phrase "object is enumerated" came up quite often. Can someone explain what happens when an object gets enumerated?
Example article.
This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C#
General explainations for enumeration
IEnumerableis an interface, that is usually implemented by collection types in C#. For exampleList,QueueorArray.IEnumerableprovides a methodGetEnumeratorwhich returns an object of typeIEnumerator.The
IEnumeratorbasically represents a "forward moving pointer" to elements in a collection.IEnumeratorhas:Current, which returns the object it currently points to (e.g. first object in your collection).MoveNext, which moves the pointer to the next element. After calling it,Currentwill hold a reference to the next object in your collection.MoveNextwill returnfalseif there were no more elements in the collection.Whenever a
foreachloop is executed on anIEnumerable, theIEnumeratoris retreived viaGetEnumeratorandMoveNextis called for each iteration - until it eventually returnsfalse. The variable you define in your loop header, is filled with theIEnumerator'sCurrent.A foreach loop is not magical
thx to @Llama
As stated above, a foreach loop is no dark magic that somehow loops through your collection and instead just a compile-time feature. Therefore, this code...
is transformed to something like this by the compiler:
The quote
GetEnumeratoris automatically called, as soon as you put your object into aforeachloop, for example. Of course, other functions, e.g. Linq queries, can also retreive theIEnumeratorfrom your collection, by doing so either explicit (callGetEnumerator) or implicit in some sort of loop, like I did in my sample above.