So, this has to be one of the more handy and obscure features of C# in .NET 2.0.
The yield keyword can only be used inside an iterator block, and what it allows you to do is easily populate a collection of items while iterating a collection of something else. The example I put together below is pretty simple. All it does is get a bunch of items from a database and then loads them into objects and uses the yield keyword to push them into the collection that is returned from the method.
Here's the method utilizing the yield keyword. Notice there's no instantiation of the collection to put the objects in, the yield keyword tells the compiler to do it for you.
And here's the calling method.
Pretty cool stuff, cuts out a few lines of code. Now, what the compiler does with this, is also equally interesting. If you open the resulting binary up with reflector, you'll find that the compiler actually turns the "GetAllMyObjects" method into an IEnumerable<MyObject> class. In this class, all the DB work is moved into the overriden MoveNext() method. Here's what it looks like:
Smart folks over there inside the C# team.