Can you help me in understanding of yield
keyword in asp .NET(C#)
.
The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created so it's more efficient. The yield operator allows the creation of items as it is demanded. That's a good reason to use it.
Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement.
When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
The yield return statement returns one element at a time. The return type of yield keyword is either IEnumerable or IEnumerator . The yield break statement is used to end the iteration. We can consume the iterator method that contains a yield return statement either by using foreach loop or LINQ query.
Yield return automatically creates an enumerator for you.
http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
So you can do something like
//pseudo code:
while(get_next_record_from_database)
{
yield return your_next_record;
}
It allows you to quickly create an object collection (an Enumerator) that you can loop through and retrieve records. The yield return statement handles all the of the code needed to create an enumerator for you.
The big part of the yield return statement is that you don't have to load all the of the items in a collection before returning the collection to the calling method. It allows lazy loading of the collection, so you don't pay the access penalty all at once.
When to use Yield Return.
Yield is much more than syntatic sugar or easy ways to create IEnumerables.
For more information I'd check out Justin Etherage's blog which has a great article explaining more advanced usages of yield.
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