Possible Duplicate:
yield statement implementation
I've seen msdn docs and it says:
The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object.
So it means yield
keyword is a Syntactic sugar and compiler does the heavy work of generating the Iterator. (Am I Correct ?)
Then what is the generated implementation code for this syntactic sugar.
yield keyword is used to create a generator function. A type of function that is memory efficient and can be used like an iterator object.
The yield keyword, first introduced in C# 2.0, T returns an object that implements the IEnumerable interface. The IEnumerable interface exposes an IEnumerator that can used to iterate a non-generic collection using a foreach loop in C#.
In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration."
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
The generated code depends on the original, but generally speaking a state machine gets generated which keeps track of the current state of the collection.
See yield statement implementation, this answer by Eric Lippert and this blog post by Jon Skeet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With