yield return expression;
yield break;
The yield statement can only appear inside an iterator block, which might be used as a body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:
· Unsafe blocks are not allowed.
· Parameters to the method, operator, or accessor cannot be ref or out.
When used with expression, a yield return statement cannot appear in a catch block or in a try block that has one or more catch clauses.
//error when use the yield statement in try block
Cannot yield a value in the body of a try block with a catch clause
7 namespace YieldExample
8 {
9 class YieldExample
10 {
11 public static class NumberList
12 {
13 // Create an array of integers.
14 public static int[] ints = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 };
15
16 // Define a property that returns only the even numbers.
17 public static IEnumerable<int> GetEven()
18 {
19 // Use yield to return the even numbers in the list.
20 foreach (int i in ints)
21 if (i % 2 == 0)
22 yield return i;
23 }
24
25 // Define a property that returns only the even numbers.
26 public static IEnumerable<int> GetOdd()
27 {
28 // Use yield to return only the odd numbers.
29 foreach (int i in ints)
30 if (i % 2 == 1)
31 yield break;
32 }
33 }
34
35 static void Main(string[] args)
36 {
37
38 // Display the even numbers.
39 Console.WriteLine("Even numbers");
40 foreach (int i in NumberList.GetEven())
41 Console.WriteLine(i);
42
43 // Display the odd numbers.
44 Console.WriteLine("Odd numbers");
45 foreach (int i in NumberList.GetOdd())
46 Console.WriteLine(i);
47 }
48 }
49 }
Comments