Use of yield in C #

Source: Internet
Author: User
Tags finally block

The yield keyword indicates to the compiler that the method in which it resides is an iterator block. The compiler generates a class to implement the behavior represented in the iterator block. In an iterator block, theyield keyword is used in conjunction with the return keyword to provide a value to the enumerator object. This is a return value, for example, the value returned in each loop of the foreach statement. The yield keyword can also be used in conjunction with break to indicate the end of the iteration.

Example:
Yield return <expression>;
Yield break;

In the yield return statement, expression is evaluated and the result is returned to the enumerator object as a value, andexpression must be implicitly convertible to the yield type's iterator.

In the yield break statement, control returns unconditionally to the caller of the iterator, which is the ienumerator.movenext of the enumerator object Method (or its corresponding generic system.collections.generic.ienumerable<t>) or the Dispose method.

The yield statement can only appear in the iterator block, which can be implemented 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 return statement cannot be placed anywhere in the Try-catch block. The statement can be placed in a try block followed by a finally block.

    • The yield break statement can be placed in a try block or catch block, but cannot be placed in a finally block.

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

When used with expression, theyield return statement cannot appear in a catch block or in a try block that contains one or more catch clauses .

I have seen the keyword "yield" for n times, until recently I have known the power of this keyword. I'll show you some examples of using "yield" to make your code more readable and better performance.

To give you a quick overview of yield, I'll start by showing an example that doesn't use this keyword, the following code is simple, but it's common in my recent projects

Ilist<string> findbobs (ienumerable<string> names) {var bobs = new list<string> (); foreach (var Currname in Names) {if (Currname = = "Bob") bobs. ADD (currname);} return bobs;}

Note here that I use ienumerable<string> as the parameter type and with Ilist<string> as the return type, and generally I prefer to have a wider range of parameters in the type aspect of the input, the better, But more stringent on the return type (the translator presses: the use of a base class or interface for input, a subclass or implementation class when returned), and for input, if you need to loop it with foreach, using IEnumerable is more meaningful. And for the output (the translator presses: that is, to return), I use the interface to make the implementation part can be changed. Here I want to let the caller save the trouble of generating the list, so I choose List as the return type.

The problem is that my design does not have a link, so the design needs to generate the list as the return value, the list may not be very large, but it is not necessary

Now, let's take a look at the "yield" way to do this, and then I'll explain how to use it and how it works.

Ienumerable<string> findbobs (ienumerable<string> names) {foreach (var currname in Names) {if (Currname = = ") Bob ") yield return currname;}}

In this version, we change the return type to IEnumerable, and we use "yield return". Notice I don't need to create a list anymore, is it a bit confusing now? Don't worry, it will become more and more simple to understand the way it works.

When you use the yield return keyword group,. NET generates a bunch of pipe code for you, and you can pretend it's a magic. When you start looping through the called code (this is not a list), what happens on the implementation is that the function is called over and over again, but each time it proceeds from the last part that executed the exit.

traditional methods of execution
    1. Calling functions
    2. function executes and returns a list
    3. The call section uses the returned list
how yield is executed
    1. Calling functions
    2. Caller requested item
    3. The next item returns
    4. Back to step 2

Although the implementation of yield execution may seem complicated, we end up with a "popup" item instead of creating the entire list and returning it.

For the syntax, I personally think that yield is more concise, and for the purpose of the transfer function is better (translator by: That is, code readability), I use IEnumerable as the return type to inform the caller that it can be a foreach loop and return data, The caller can now decide for itself whether it is willing to store the return value in the list, even if it is at the expense of performance.

In this simple example that I have provided, you may not be able to find many benefits of using yield, however, you can save a lot of unnecessary work when the caller needs to cancel the content provided by all functions, and when you use yield on the method link, the amount of work (time) You can save may multiply.

Ayende has a great example: the using yield for a slick pipes & filters implementation, he even tells: version is multi-threaded. It makes me feel very interesting.

At first my reservation to yield was that using this keyword might lead to potential performance problems, but in fact, so far I have not found any information to illustrate the impact of yield on performance, which I mentioned above is far greater than the compiler overhead part.

Use of yield in C #

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.