| 1 | = Yield = |
| 2 | |
| 3 | The '''yield''' keyword signals to the compiler that the method in which it |
| 4 | appears is an iterator block. [[BR]] |
| 5 | A new class is created and compiled to implement the behavior that is |
| 6 | expressed in the iterator block (implementing an IEnumerable). |
| 7 | |
| 8 | Within the iterator block, the yield keyword is used to provide a value to |
| 9 | the enumerator object.[[BR]] |
| 10 | This is the value that is returned, for example, in each loop of a |
| 11 | for statement. |
| 12 | |
| 13 | In a '''yield''' statement, the expression is evaluated and returned as |
| 14 | a value to the enumerator object; expression has to be implicitly |
| 15 | convertible to the yield type of the iterator. |
| 16 | |
| 17 | In a '''yield break''' statement, control is unconditionally returned to the |
| 18 | caller of the iterator and signals the end of iteration. |
| 19 | |
| 20 | |
| 21 | The yield statement can only appear inside an iterator block, |
| 22 | which can be implemented as the body of a method, operator, or accessor. |
| 23 | |
| 24 | * A '''yield''' statement cannot be located anywhere inside a try-catch block. |
| 25 | It can be located in a try block if the try block is followed by a |
| 26 | finally block. |
| 27 | * A '''yield break''' statement may be located in a try block or a |
| 28 | catch block but not a finally block. |
| 29 | |
| 30 | == Grammar == |
| 31 | {{{ |
| 32 | yield [EXPRESSION] |
| 33 | |
| 34 | yield break |
| 35 | }}} |
| 36 | == Example == |
| 37 | {{{ |
| 38 | use System.Collections |
| 39 | |
| 40 | class Pwr |
| 41 | def power(num as int, exponent as int) as IEnumerable is shared |
| 42 | counter = 0 |
| 43 | result = 1 |
| 44 | while counter < exponent |
| 45 | counter += 1 |
| 46 | result = result * num |
| 47 | yield result |
| 48 | yield break |
| 49 | |
| 50 | def main is shared |
| 51 | # Display powers of 2 up to the exponent 8: |
| 52 | for i in .power(2, 8) |
| 53 | print i |
| 54 | /# |
| 55 | Output: |
| 56 | 2 4 8 16 32 64 128 256 |
| 57 | #/ |
| 58 | }}} |