YIELD
|
|
|
NSupported in Synergy .NET
|
YIELD MRETURN expression
or
YIELD EXIT
Arguments
expression
An expression that is evaluated and returned as a value to the enumerator object.
Discussion
The YIELD statement indicates to the compiler that the current method is an iterator block. The two versions of the YIELD syntax perform different functions:
- YIELD MRETURN expression gives the next value from the iteration (i.e., the value returned in each iteration of a FOREACH statement). It causes an element in the source sequence to be returned immediately to the caller before the next element in the sequence is accessed.
- YIELD EXIT indicates the end of iteration. Control returns to the caller of the iterator block.
Although an iterator is written as a method, the compiler translates it into a nested class that keeps track of the position of the iterator as long as the FOREACH loop on the client code continues. When YIELD MRETURN is reached, the current location is stored. Execution begins at this location the next time the iterator is called.
An iterator method must have a return type of IEnumerable or IEnumerable<> (or IAsyncEnumerable<T> if the method has both ASYNC and YIELD). A class can have multiple iterators.
A YIELD MRETURN statement cannot appear in a CATCH block, a TRY block that contains a CATCH, or a FINALLY block.
Examples
The example below returns powers of 2 using the YIELD statement.
import System.Collections namespace ns1 public class PowersOf2 public static method Power, @IEnumerable number, int exponent, int proc data counter, int, 0 data result, int, 1 while (counter < exponent) begin incr counter result = result * number yield mreturn result end endmethod endclass endnamespace main proc data i, int foreach i in ns1.PowersOf2.Power(2,8) begin Console.Write(i) Console.Write(" ") end Console.WriteLine()