Search This Blog

Saturday, March 29, 2014

Introduction to Yield Statement in VB.Net

The Yield Statement in VB.Net

The Yield statement returns one element of a collection at a time. The Yield statement is included in an iterator function or Get accessor, which perform custom iterations over a collection.
You consume an iterator function by using a For Each...Next Statement (Visual Basic) or a LINQ query. Each iteration of the For Each loop calls the iterator function. When aYield statement is reached in the iterator function, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
An implicit conversion must exist from the type of expression in the Yield statement to the return type of the iterator.
You can use an Exit Function or Return statement to end the iteration.
"Yield" is not a reserved word and has special meaning only when it is used in an Iterator function or Get accessor.

Iterator Functions and Get Accessors

The declaration of an iterator function or Get accessor must meet the following requirements:
  • It must include an Iterator modifier.
  • The return type must be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.
  • It cannot have any ByRef parameters.
  • An iterator function can be an anonymous function. For more information
An iterator function cannot occur in an event, instance constructor, static constructor, or static destructor.

Exception Handling in Yield 


Yield statement can be inside a Try block of a Try...Catch...Finally Statement (Visual Basic). A Try block that has a Yield statement can have Catch blocks, and can have aFinally block.
Yield statement cannot be inside a Catch block or a Finally block.
If the For Each body (outside of the iterator function) throws an exception, a Catch block in the iterator function is not executed, but a Finally block in the iterator function is executed. A Catch block inside an iterator function catches only exceptions that occur inside the iterator function.

An Example:
Sub Main()
    For Each number In Power(2, 8)
        Console.Write(number & " ")
    Next 
    ' Output: 2 4 8 16 32 64 128 256
    Console.ReadKey()
End Sub 

Private Iterator Function Power(
ByVal base As Integer, ByVal highExponent As Integer) _
As System.Collections.Generic.IEnumerable(Of Integer)

    Dim result = 1

    For counter = 1 To highExponent
        result = result * base
        Yield result
    Next 
End Function

No comments:

Post a Comment