Is yield return
a shortcut for implementing IEnumerable
and IEnumerator
?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With