Wiki
Version 1 (modified by hopscc, 15 years ago)

--

Yield

The yield keyword signals to the compiler that the method in which it appears is an iterator block.
A new class is created and compiled to implement the behavior that is expressed in the iterator block (implementing an IEnumerable).

Within the iterator block, the yield keyword is used to provide a value to the enumerator object.
This is the value that is returned, for example, in each loop of a for statement.

In a yield statement, the expression is evaluated and returned as a value to the enumerator object; expression has to be implicitly convertible to the yield type of the iterator.

In a yield break statement, control is unconditionally returned to the caller of the iterator and signals the end of iteration.

The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor.

  • A yield statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.
  • A yield break statement may be located in a try block or a catch block but not a finally block.

Grammar

yield [EXPRESSION]

yield break

Example

use System.Collections

class Pwr
    def power(num as int, exponent as int) as IEnumerable is shared
        counter = 0
        result  = 1
        while counter < exponent
            counter += 1
            result = result * num
            yield result
       yield break    

    def main is shared
        # Display powers of 2 up to the exponent 8:
        for i in .power(2, 8)
            print i
/#
Output:
2 4 8 16 32 64 128 256 
#/