Use the yield keyword in C #2.0 to simplify the implementation of the enumerator.

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.