A detailed example of foreach and yield in C #

Source: Internet
Author: User
Tags finally block
1. Foreach

The C # compiler converts the foreach statement to the methods and properties of the IEnumerable interface.


foreach (person p in persons) {     Console.WriteLine (p);}

The foreach statement resolves to the following code snippet.

Call the GetEnumerator () method to get an enumeration of the array

In the while loop, as long as MoveNext () returns True, the loop continues

Accessing elements in an array with the current property


IEnumerator Enumerator = persons. GetEnumerator (); while (enumerator. MoveNext ()) {person    P = (person) Enumerator. Current;    Console.WriteLine (P);}

2. Yield statement

Two forms of the yield statement:


Yield return <expression>;yield break;

Returns an element of a collection using a yield return statement

The method or property that contains the yield statement is an iterator. Iterators must meet the following requirements

A. The return type must be IEnumerable, ienumerable<t>, IEnumerator, or ienumerator<t>.

B. It cannot have any ref or out parameters

The yield return statement cannot be located try-catch fast. The yield return statement can be located in a try block of try-finally


Try              {                  //Error:cannot yield a value in the boday of a try block with a catch clause                 yield return "test";              }             catch             {}               try             {                 //                  yield return "test again";             }             Finally             {}              try             {}             finally             {                  //error:cannot yield in the body of a finally clause                Yi Eld return "";              }

The yield break statement can be in a try block or catch block, but not in a finally block

The following example is the code for implementing a simple collection with the yield return statement, and iterating over the collection with a foreach statement


Using system;using system.collections.generic;namespace consoleapplication6{    class program    {        static void Main (string[] args)        {            hellocollection hellocollection = new Hellocollection ();            foreach (string s in hellocollection)            {                Console.WriteLine (s);                Console.ReadLine ();    }}} public class Hellocollection    {public                ienumerator<string> GetEnumerator ()        {            //yield The return statement returns an element of the collection and moves to the next element; yield break can stop            the iteration yield return "Hello";            Yield return "World";}}    }

Use the yield return statement to implement classes that iterate the collection in different ways:


Using system;using System.collections.generic;namespace consoleapplication8{class Program {static void Main        (string[] args)            {Musictitles titles = new Musictitles ();            foreach (string title in titles) {Console.WriteLine (title);            } Console.WriteLine (); foreach (string title in titles.            Reverse ()) {Console.WriteLine (title);            } Console.WriteLine (); foreach (string title in titles.                Subset (2, 2)) {Console.WriteLine (title);            Console.ReadLine ();        }}} public class Musictitles {string[] names = {"A", "B", "C", "D"};                Public ienumerator<string> GetEnumerator () {for (int i = 0; i < 4; i++) {            Yield return names[i]; }} public ienumerable<string> Reverse () {foR (int i = 3; I >= 0; i--) {yield return names[i];  }} public ienumerable<string> subset (int index, int length) {for (int i = index; i < index + length;            i++) {yield return names[i]; }        }    }}

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.