-1

I came across these two code snippets while reading about IEnumerable interfaces. I would like to understand the exact difference between them in simple terms.

Snippet 1 : without yield,

    public IEnumerator GetEnumerator()
    {
        // Return the array object's IEnumerator.
        return carArray.GetEnumerator();
    }

Snippet 2:with yield,

    public IEnumerator GetEnumerator()
    {
        foreach (Car c in carArray)
        {
            yield return c;
        }
    }

Both the snippets do the same work, So whats so specific in using YIELD over here?

Thanks in advance :)

cf-
  • 8,598
  • 9
  • 36
  • 58
Sadhun
  • 264
  • 5
  • 14

3 Answers3

1

yield return turns your stateful sequential code into an iterator.

Instead of having a separate class to manage the iterator position, like in the first example, you can iterate in code and "return" each value as you visit it. This is not a conventional return, it's a yield which is more of a context switch to the code calling you. The next iteration will resume you.

Rhythmic Fistman
  • 34,352
  • 5
  • 87
  • 159
1

The essence about yield is that it deferres actual execution to the time, when the value is really queried. In other words, a particular value is evaluated not at the time you ask for the enumerator, but at the time when the value is retrieved (lazy evaluation).

This has a number of implications:

  • there is no need for (potentially huge) resource allocation to build the collection upfront
  • when the enumeration terminates prematurely, values that are never queried must not be returned
JensG
  • 13,148
  • 4
  • 45
  • 55
0

Ah, but there is a difference! yield return is a bit of syntactic sugar that yields control back to the calling function. It provides optimization opportunities so that if you know you are looking for a certain value in a collection, you don't have to return the whole collection to the caller, you can short-circuit the enumeration once you get what you need.

So how does it do it? yield return gets turned into a switch statement, which is described here: http://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/

There is a really good video that also explains it here: https://www.youtube.com/watch?v=Or9g8LOhXhg

Mister Epic
  • 16,295
  • 13
  • 76
  • 147