How to Use the yield return keyword?

Source: Internet
Author: User
Q: How to Use the yield return keyword?

Answer:

The iterator block is used to provide a value to the enumerated number object or send an iteration end signal. It is in the form of one of the following:

CopyCode
Yield return <expression>;
Yield break;

Remarks
Calculates the expression and returns it in the form of an enumerated object value. The expression must be implicitly converted to the yield type of the iterator.

The yield statement can only appear in the iterator block. This block can be used as a method, operator, or accessors. These methods, operators, or accessors are subject to the following constraints:

Insecure blocks are not allowed.

The parameters of methods, operators, or accessors cannot be ref or out.

Yield statements cannot appear in anonymous methods. For more information, see the anonymous method (C # programming guide ).

When used together with expression, the yield return statement cannot appear in catch blocks or try blocks that contain 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 (the method power (INT number, int power. When the power method is called, it returns an enumerative object containing the number power. Note that 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

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.