

Local variables initialized inside yield methods, retain their values between MoveNext method calls. If you call the GetInts method once more, it will return a new object that will allow you to start generating new elements. Further MoveNext method's calls will have no effect and will also return false. Since the GetInts method contains no more code, the third MoveNext method call will return false. The console will display the "second" message, and 2 will be recorded to the Current property.Ĭalling MoveNext for the third time will start executing the GetInts method from the moment it was earlier suspended. The next time you call MoveNext again, the method's execution will pick up where it left off. Thus, this code's first output is ".", then "first", and at the end "1" - a value from the Current property. The value specified in the yield return is assigned to the Current property. The MoveNext method's first call executes the code inside GetInts - until the first yield return. Then the method exits before it can reach any other code. When the GetInts function is called, it returns an object that implements IEnumerator. IntsEnumerator.MoveNext() // print "first"Ĭonsole.WriteLine(intsEnumerator.Current) // print 1 IEnumerator intsEnumerator = GetInts() // print nothing Take a look at this simple yield method: static IEnumerator GetInts() Though you can use yield in methods, properties and operators, to simplify this article I'll review only methods. The only limitation here is that the method must return one of the following types: To begin, create a method that generates the sequence you need. Which is why here's one more reminder that this article talks about yield only in the context of C#. However, while the concept is the same, in different languages yield may be implemented and used differently. I must point out here that yield is not a feature available exclusively in C#.

You do not have to create new classes - everything works already. While there is nothing wrong with writing a class to implement the generator's behavior, yield simplifies creating such generators significantly. This is often much more convenient than creating a collection and storing all of its elements. In the simplest scenario, the generator stores the current element and contains a set of commands that must be executed to get a new element. It's not hard to guess that generated sequences can be infinite. Thus, memory requirements are minimal and do not depend on the number of elements. Instead, the sequence stores the current state - and moves on to the next state on command. These generators do not create collections. The yield keyword is used to build generators of element sequences.
