Yield is 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: yield return <expression>;yield break; 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: L do not allow unsafe blocks. The parameters of the L method, operator, or accessor cannot be ref or out. The yield statement cannot appear in an anonymous method. 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. 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). Using system;using system.collections.generic;using system.linq;using system.text; Using System.Collections; Namespace mvcusedkeywords{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 (string[] args) { Show 2 X-side (1<=x<=8) IEnumerable t = Power (2, 8); foreach (int i in t) {Console.Write ("{0}", i); }}} Results: 2 4 8 16 32 64 128 256
. NET yield return