CUAHIS-HIS
RSS

Navigation





Quick Search
»
Advanced Search »

PoweredBy

C# yield

RSS
Modified on 2009/10/23 13:26 by valentinedwv Categorized as Uncategorized
http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html

http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx

{@code-csharp:

IList FindBobs(IEnumerable names) {

var bobs = new List();

foreach(var currName in names) {

if(currName == "Bob")

bobs.Add(currName);

}

return bobs;

}



@}

Notice that I take in an IEnumerable<string>, and return an IList<string>. My general rule of thumb has been to be as lenient as possible with my input, and as strict as possible with my output. For the input, it clearly makes sense to use IEnumerable if you’re just going to be looping through it with a foreach. For the output, I try to use an interface so that the implementation can be changed. However, I chose to return the list because the caller may be able to take advantage of the fact that I already went through the work of making it a list.

The problem is, my design isn’t chainable, and it’s creating lists all over the place. In reality, this probably doesn’t add up to much, but it’s there nonetheless.

Now, let’s take a look at the "yield" way of doing it, and then I’ll explain how and why it works:

{@code-csharp: IEnumerable FindBobs(IEnumerable names) {

foreach(var currName in names) {

if(currName == "Bob") yield return currName;

}

} @}

In this version, we have changed the return type to IEnumerable, and we’re using "yield return". Notice that I’m no longer creating a list. What’s happening is a little confusing, but I promise it’s actually incredibly simple once you understand it.

When you use the "yield return" keyphrase, .NET is wiring up a whole bunch of plumbing code for you, but for now you can pretend it’s magic. When you start to loop in the calling code (not listed here), this function actually gets called over and over again, but each time it resumes execution where it left off.

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam.