Thursday, 12 March 2009

yield and iterators

I've just implemented an iterator using the new c#2 yield keyword, it took me about 5 mins and worked so easy. I love this new feature. It makes things so easy.

I had a DateTimeRange class and I needed to get the first day of every month that was covered by the range.

Here is the code:

   49 public IEnumerable<DateTime> MonthStarts

   50 {

   51     get

   52     {

   53         var current = new DateTime(Start.Year, Start.Month, 1);

   54 

   55         while (current <= End)

   56         {

   57             yield return current;

   58             current = current.AddMonths(1);

   59         }

   60     }

   61 }



This can then be used in simple foreach statements.

Submit this story to DotNetKicks Shout it

No comments:

Post a Comment