Showing posts with label yield. Show all posts
Showing posts with label yield. Show all posts

Tuesday, 9 June 2009

Code Generation - yield and Lambdas

So, while I don't profess to be an expert on Code Generation, I do hope that some of the tips that I put up here may save someone else the time it took me to figure out how to accomplish what appear to be simple steps.

At the time of writing this post, and having spent several hours scouring the internet, I couldn't for the life of me find a way to get a yield return statement.

The reason for this will be explained in another post (TODO:addlink) but the basic premise was to have the following line in the generated class:

   01 yield return () => SomeStringProperty;

All the properties returned strings, so this was fine.

Trying to generate this was proving a problem, until I came across this...hmm...workaround (don't want to use the word hack here)
While it ties the generated code to be specifically C#, this, again was not a problem for the code base that we were working against.

Here is the code that produced the line:

  01 generatedProperty.GetStatements.Add(new CodeSnippetExpression(string.Format("yield return () => {0}", existingProperty.Name)));

The genereatedProperty is of type CodeMemberProperty as is the existingProperty.

I wouldn't recommend this for all solutions, but it worked in this case where we were not trying to add to a generic code generator.

Submit this story to DotNetKicks Shout it

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