22

I have a vague understanding of the yield keyword in , but I haven't yet seen the need to use it in my code. This probably comes from a lack of understanding of it.

So, what are some typical good usages of yield?

4
  • There is a very good answer regarding the Yield keyword here Commented Apr 23, 2010 at 7:30
  • 3
    Try this first: stackoverflow.com/search?q=yield+c%23, the first page of results has at least 5 questions which should help you. Commented Apr 23, 2010 at 7:30
  • Oh, thanks! A lot of useful stuff there! Commented Apr 23, 2010 at 7:34
  • possible duplicate of stackoverflow.com/questions/39476/… Commented Apr 23, 2010 at 12:47

4 Answers 4

14

yield just makes it very simple to implement an enumerator. So if you wanted write a method that returns an IEnumerable<T> it saves you having to create the enumerator class - you just yield one result at a time and the compiler takes care of the details under the covers.

One handy case is to write an "infinite enumerator" that the caller can call as many times as it needs to. Here's an example that generates an infinite series of Fibonacci numbers: http://chrisfulstow.com/fibonacci-numbers-iterator-with-csharp-yield-statements/ (well... theoretically infinite, but in practice limited to the size of UInt64).

Sign up to request clarification or add additional context in comments.

Comments

4

Yield implements the pattern of lazy loading. I suggest to consider its usefulness from this perspective.

For example. in the context of business software I'm working on, it could brings the advantage of lowering load on the database. You write code that pulls a variety of data from the database, but only that portion will be loaded which is really needed for a particular scenario. If a user doesn't go deeper in the UI, the respective data will not be loaded.

1 Comment

That was a really useful example that demonstrates that you have a long list that might not be used fully.
4

Yield is used in enumerators. The C# compiler automatically pauses execution of your enumeration loop and returns the current value to the caller.

IEnumerable<int> GetIntegers(int max) {
    for(int i = 1; i <= max) {
         yield return i; // Return current value to the caller
    }
}

-- or (more clunky) --

IEnumerable<int> GetIntegers(int max) {
    int count = 0;
    while(true) {
         if(count >= max) yield break; // Terminate enumeration

         count++;
         yield return count; // Return current value to the caller
    }
}

More details on MSDN.

Comments

3

Also pretty good in testing and mocking when you just want to test an IEnumerable<> quickly, something like...

yield return somevalue;
yield return someothervalue;
yield return yetanotherone;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.