tags:

views:

231

answers:

6

Hi Experts, can you help me in understanding of yield keyword in asp.net(C#).

Thanks Vij

+10  A: 

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.

Kevin
A: 

yield is used as syntactic sugar to return an IEnumerable<T> or IEnumerator<T> object from a method without having to implement your own class implementing these interfaces.

spoulson
?? Why the downvotes? Am I incorrect?
spoulson
Yes, because it is different from creating the IEnumerable yourself and returning it.
Jouke van der Maas
There is nothing incorrect about this answer.
Brian Gideon
If you examine the MSIL using .NET Reflector, you can see that C# creates a hidden class implementing `IEnumerable<T>` that is fed by `yield return` statements. So, at a high level, it is not different than implementing your own `IEnumerable<T>` class, instantiating and returning it.
spoulson
Because calling yield "syntactic sugar" doesn't encompass its true potential. Your answer is harmful. What if somebody walks away after reading this and says "I won't use yield, its just syntactic sugar"
jfar
A: 

yield allows you to emit an IEnumerable where you'd normally return a more concrete type (like an IList).

This is a pretty good example of how it can simplify your code and clarify your intent. As for where you'd use it, anywhere on your pages that you need to iterate over a collection you could potentially use a method that returns an IEnumerable in place of a List/Dictionary/etc.

48klocs
+4  A: 

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.

jfar
Absolutely. You cannot fully appreciate `yield` until you understand exactly how it is creating the state machine for you. It is incredibly powerful.
Brian Gideon
Damn thats helpful. I know this is old but that post really did it for me.
Terrance
+1  A: 

I wrote a simple sample showing how the yield block is invoked during a visiting cycle of the collection. Check it out here.

Hemme