newprint
newprint

Reputation: 7136

How yield return is interpreted by foreach loop ?

How yield return is interpreted by foreach loop ?

foreach loop looks something like this:

var tmp = obj.GetEnumerator();
int i; // up to C# 4.0
while(tmp.MoveNext()) {
    int i; // C# 5.0
    i = tmp.Current;
    {...} // your code
}

As far as I understood, compiler must somehow substitute yield return with MoveNext() & Current(property) from IEnumerable/IEnumerable interface.

Upvotes: 1

Views: 116

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

Compiler creates a state machine which moves to next state every time you call MoveNext() and return proper value for current state by Current property.

This state machine may be infinite (e.g. when you place yield return inside infinite loop) or finite. When it's finite as the last state MoveNext() returns false to let caller know that there are no more results.

There is pretty nice article about that by Jon Skeet: Iterator block implementation details: auto-generated state machines.

Upvotes: 5

Related Questions