0

I know what yield return is, but I can't understand why should I use it, is it just because it saves me a row of a list declaration?

It must be something more to it.

What is it and where it is best to use it?

*I asked where and why to use it , whats its advantages and not what is it.

Dr.Haimovitz
  • 1,568
  • 12
  • 16

3 Answers3

6

is it just because it saves me a row of a list declaration?

No. When you use yield you get Deferred Execution. This means that you create the items to yield as the consumer is consuming the items.

If you add items to the list and then return it, then you have to create all items before the consumer can consume any of them.

For example, assume that the consumer calls your method and uses a for loop to consume it like this:

foreach(var item in GetMyLovelyItems())
{
   ...
}

If the GetMyLovelyItems returns a list, then all items will be created before the GetMyLovelyItems method returns and the loop starts.

If on the other hand, you use yield to return items, then the items will be created as the loop goes from one iteration to the next one.

Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
2

It's for those complicated cases where you cannot make due with an array, a list or the Enumerable.* methods. This feature is needed quite rarely.

The most common usage pattern is emitting items in some kind of loop that cannot be expressed with the Enumerable.* methods.

Many Enumerable methods are implemented with yield.

yield is not required for deferred execution. Enumerable is deferred as well.

In any case you can write your own IEnumerable derived class. This is the most expressive and the most tedious way to produce a sequence.

usr
  • 168,620
  • 35
  • 240
  • 369
2

It can possibly be also coupled with delayed/deffered execution of the code that generates the yield

Jigar
  • 544
  • 1
  • 8
  • 28