Used in an iterator block to provide a value to an enumerator object or to emit an iterative end signal. It is in the form of one of the following:
Copy Code
Yield return <expression>;
Yield break;
Note
Evaluates an expression and returns it as an enumerator object value, and expression must be implicitly convertible to the yield type of the iterator.
The yield statement can only appear in a iterator block, which can be used as the body of a method, operator, or accessor. The body of such a method, operator, or accessor is controlled by the following constraints:
Unsafe blocks are not allowed.
The parameters of a method, operator, or accessor cannot be ref or out.
The yield statement cannot appear in an anonymous method. For more information, see Anonymous Methods (C # Programming Guide).
When used with expression, the yield return statement cannot appear in a catch block or in a try block that contains one or more catch clauses. For more information, see Exception Handling statements (C # Reference).
Example
In the following example, the yield statement is used in the iterator block (here is method Power (int number, int power). When the power method is called, it returns an enumerable object that contains the power of a number. Note The return type of the Power method is IEnumerable (an iterator interface type).
Copy Code
Yield-example.cs
Using System;
Using System.Collections;
public class List
{
public static IEnumerable Power (int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
static void Main ()
{
Display powers of 2 up to the exponent 8:
foreach (int i in Power (2, 8))
{
Console.Write ("{0}", i);
}
}
}
Copy Code
2 4 8 16 32 64 128 256
How does the yield return keyword work?