Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Yield Return == IEnumerable & IEnumerator?

Is yield return a shortcut for implementing IEnumerable and IEnumerator?

like image 419
John Avatar asked Nov 13 '08 23:11

John


People also ask

What is a yield return?

Yield is the income returned on an investment, such as the interest received from holding a security. The yield is usually expressed as an annual percentage rate based on the investment's cost, current market value, or face value.

What is the return type of IEnumerable?

IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).

How does yield return work in C#?

You use a yield return statement to return each element one at a time. The sequence returned from an iterator method can be consumed by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method.

What is the difference between yield and return in C#?

The only difference between yield and return is whenever yield statement is encountered in a function, the execution of function is suspended and a value is send back to the caller but because of yield whenever the function is called again, the execution of function begin where it left off previously.


1 Answers

Yes, it is.

You can find out a lot more about it in chapter 6 of my book, C# in Depth. Fortunately chapter 6 is available for free from Manning's web site.

I also have two other articles on the book's web site.

Feedback welcome.

like image 169
Jon Skeet Avatar answered Sep 22 '22 19:09

Jon Skeet