How does the yield return keyword work?

Source: Internet
Author: User

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:

Copy Code
Yield return <expression>;
Yield break;

Note
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:

Unsafe blocks are not allowed.

The parameters of a method, operator, or accessor cannot be ref or out.

The yield statement cannot appear in an anonymous method. For more information, see Anonymous Methods (C # Programming Guide).

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. For more information, see Exception Handling statements (C # Reference).

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).

Copy Code
Yield-example.cs
Using System;
Using System.Collections;
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 ()
{
Display powers of 2 up to the exponent 8:
foreach (int i in Power (2, 8))
{
Console.Write ("{0}", i);
}
}
}

Copy Code
2 4 8 16 32 64 128 256

How does the yield return keyword work?

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.