Know When to ‘yield’ (C# goodies)
One of the fun things as I have begun working more in C# is that I’m finally able to leverage all those fancy language features that do not have a VB equivalent. The other day I was reviewing code with the project architect and he caught me using the yield keyword. He thought it was a good use of yield and we ended up changing several interfaces to return IEnumerable<T> so we could leverage yield and a few other .NET 3.5 features.
When to yield
The yield keyword allows you to build up results within an iterator statement and return a type derived from IEnumerable (or IEnumerable<T>). In MSDN speak:
Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration.
Let’s take a look at the following code that gets an IEnumerable of Wishlist Items:
public IEnumerable<WishlistItem> GetAll() { ///boring database code here var i = 0; var items = new List<WishlistItem>(); while (i < 5) { items.Add(new WishlistItem("Item" + i, "Item" + i + " details", new Uri("http://localhost/item/" + 1))); i++; } return items; }
Using yield we can rewrite the same code as follows:
public IEnumerable<WishlistItem> GetAllWithYield() { ///boring database code here var i = 0; while (i < 5) { yield return new WishlistItem("Item" + i, "Item" + i + " details", new Uri("http://localhost/item/" + 1)); i++; } }
Comments are closed.


December 23, 2009 - 1:11 pm
Nice! You can see how far we’ve come since C# 1.0. Generics, the var keyword, yield …