Skip to main content

Posts

Showing posts from March, 2012

Deferred execution in C#

A lot of times, fellow developers ask me about yield return keyword and what this keyword is for. This keyword allows us to iterate over enumerable collections in a more efficient way. Basically what does is tells the compiler do not execute this code unless is strictly necessary (for this reason it’s also called lazy evaluation). I wrote a little sample that shows the keyword in action. The purpose of this code is to convert a DataTable into a Collection of objects. Maybe the algorithm is not the best way to accomplish the job but clearly shows how yield return works. To see the advantages of lazy evaluation we first should take look at how the code will work if we don’t use it. Here I convert a DataTable that contains four rows into a collection of objects and take the first element from the result. This version of convert works eagerly. And the result is: As we can see this in the output window, this version of the convert method walks thru the whole rows collection converting ea