We know that to use the foreach statement to call the iterator from the client code, we must implement the IEnumerable interface to publish the enumerator. IEnumerable is used to publish the enumerator and does not implement the enumerator, to implement the enumerator, you must implement the IEnumerator interface. Now, you do not need to implement the entire IEnumerator interface with the yield keyword. This simplifies the code and enables more flexible enumeration.
The following code:
1 // Declare the collection:
2 public class SampleCollection
3 {
4 public int [] items;
5
6 public SampleCollection ()
7 {
8 items = new int [5] {5, 4, 7, 9, 3 };
9}
10
11 public System. Collections. IEnumerable BuildCollection ()
12 {
13 for (int I = 0; I <items. Length; I ++)
14 {
15 yield return items [I];
16}
17}
18}
19
20 class MainClass
21 {
22 static void Main ()
23 {
24 SampleCollection col = new SampleCollection ();
25
26 // Display the collection items:
27 System. Console. WriteLine ("Values in the collection are :");
28 foreach (int I in col. BuildCollection ())
29 {
30 System. Console. Write (I + "");
31}
32}
33}
34
Or
Code
1 class Program
2 {
3 static void Main (string [] args)
4 {
5 SampleCollection s = new SampleCollection ();
6
7 foreach (int I in s)
8 {
9 Console. WriteLine (I. ToString ());
10}
11}
12}
13
14 public class SampleCollection: IEnumerable
15 {
16 public int [] items;
17
18 public SampleCollection ()
19 {
20 items = new int [5] {5, 4, 7, 9, 3 };
21}
22
23 public IEnumerator GetEnumerator ()
24 {
25 for (int I = 0; I <items. Length; I ++)
26 {
27 yield return items [I];
28}
29}
30}
Note that the yield keyword is added to C #2.0, which simplifies the implementation of the enumerator. However, it only changes the compiler. In fact, the compiler helps us implement the enumerator of the IEnumerator interface.