Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is 'yield' keyword a syntactic sugar ? What is its Implementation [duplicate]

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.

like image 607
Shekhar_Pro Avatar asked Nov 27 '11 12:11

Shekhar_Pro


People also ask

What is the use of yield keyword?

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.

What is the yield keyword used for and what interface is it commonly used in conjunction with?

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#.

What is the use of yield keyword in C# with example?

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."

What is syntactic sugar in C?

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.


1 Answers

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.

like image 171
Oded Avatar answered Sep 27 '22 23:09

Oded