Wiki

Changes between Initial Version and Version 1 of Yield

Show
Ignore:
Timestamp:
03/23/10 11:56:14 (15 years ago)
Author:
hopscc
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Yield

    v1 v1  
     1= Yield = 
     2 
     3The '''yield'''  keyword signals to the compiler that the method in which it  
     4appears is an iterator block. [[BR]] 
     5A new class is created and compiled to implement the behavior that is  
     6expressed in the iterator block (implementing an IEnumerable). 
     7 
     8Within the iterator block, the yield keyword is used to provide a value to  
     9the enumerator object.[[BR]]  
     10This is the value that is returned, for example, in each loop of a  
     11for statement.  
     12 
     13In a '''yield''' statement, the expression is evaluated and returned as  
     14a value to the enumerator object;  expression has to be implicitly  
     15convertible to the yield type of the iterator. 
     16 
     17In a '''yield break''' statement, control is unconditionally returned to the  
     18caller of the iterator and signals the end of iteration.  
     19 
     20 
     21The yield statement can only appear inside an iterator block,  
     22which 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{{{ 
     32yield [EXPRESSION] 
     33 
     34yield break 
     35}}} 
     36== Example == 
     37{{{ 
     38use System.Collections 
     39 
     40class 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/# 
     55Output: 
     562 4 8 16 32 64 128 256  
     57#/ 
     58}}}