Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is yield and what is the benefit to use yield in asp .NET?

Tags:

yield

c#

asp.net

Can you help me in understanding of yield keyword in asp .NET(C#).

like image 711
Vijjendra Avatar asked Jul 07 '10 13:07

Vijjendra


People also ask

What is the benefit of yield 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.

What is the yield keyword used for?

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.

What is yield in MVC?

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.

What is yield return in C #?

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.


2 Answers

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.

like image 120
kemiller2002 Avatar answered Oct 17 '22 17:10

kemiller2002


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.

like image 24
John Farrell Avatar answered Oct 17 '22 15:10

John Farrell