tags:

views:

879

answers:

6

Possible Duplicate:
What is the yield keyword used for in C#?

I've recently noticed the "yield" keyword and it caught my attention. English is not my primary language so the meaning of the word itself may elude me as well. What does that keyword mean in C# and how is it used?

+3  A: 

The yield keyword is used when implementing enumerators.

Here's a blog post with an example.

svinto
+10  A: 

yield is a contextual keyword used in iterator methods in C#. Basically, it has two use cases:

  • yield return obj; returns the next item in the sequence.
  • yield break; stops returning sequence elements (this happens automatically if control reaches the end of the iterator method body).
Mehrdad Afshari
+3  A: 

From MSDN

In a yield return statement, expression is evaluated and returned as a value to the enumerator object; expression has to be implicitly convertible to the yield type of the iterator.

In a yield break statement, control is unconditionally returned to the caller of the iterator, which is either the IEnumerator..::.MoveNext method (or its generic [T:System.Collections.Generic.IEnumerable'1] counterpart) or the Dispose method of the enumerator object.

The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:

* Unsafe blocks are not allowed.
* Parameters to the method, operator, or accessor cannot be ref or out.
* A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.
* A yield break statement may be located in a try block or a catch block but not a  finally block.

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

When used with expression, a yield return statement cannot appear in a catch block or in a try block that has one or more catch clauses. For more information, see Exception Handling Statements (C# Reference) .

David Basarab
+8  A: 

The yield keyword was introduced in C# 2.0 (it is not currently available in VB.NET) and is useful for iteration. In iterator blocks it can be used to get the next value.

You implement it with a return statement, which will return the value to the enumerator object. You can use it to foreach over a collection. Example taken from the previous MSDN link:

// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 8))
{
    Console.Write("{0} ", i);
}

public static IEnumerable Power(int number, int exponent)
{
    int counter = 0;
    int result = 1;
    while (counter++ < exponent)
    {
     result = result * number;
     yield return result;
    }
}

This produces the output: 2 4 8 16 32 64 128 256

Each iteration in the foreach block is given the next value from the IEnumerable Power method until no further results to yield are available.

Ahmad Mageed
+7  A: 

Yield is not only for iteration or enumeration. It's also a great way to encapsulate state.

Anders Rune Jensen
that's interesting, are there any examples?
Maciek
yield return 1; yield return 2; there that builds a simple finite state machine, each call to MoveNext on the enumerator resumes from the previous state then runs until the next yield, which is the next state.
KeeperOfTheSoul
the idea is to think of yielding as creating a closure which encapsulates the state of all the variables on the stack. That might simply be something like int i = 0; yield return i++;, but could be much more advanced. I'd recommend to look at functional languages, especially lisp for good examples of this technique.
Anders Rune Jensen
There's a nice series of blog entries by Raymond Chen on this - http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx
Henrik Opel
A: 

I won't repeat code examples as there are some in above answers.

Yield is useful if you want to get items in a sequence, but the sequence is costly to retrieve or calculate. Using yield allows you to only retrieve\calculate each item as it is asked for, thus allowing you to spread the cost of the calculations and preventing you from wasted time\effort on items that are not asked for.

For example, it you have a system for generating invoice numbers that involves aggregating details from the seller and customer combined with a counter to give a unique reference number within a given seller\customer contract. You may have to retrieve a number of items from data storage, double check that the new reference number has not already been used and then store the new reference number to prevent duplication. This is potentially a lot of effort. Using the yield keyword would allow you to create a class that appeared to be an enumeration that you could access as you processed orders, thus simplifying the processing code.

Dr Herbie