Wednesday, April 9, 2008

T4 and the framework 3.5...

I have been playing around with the T4 template engine for the last few days now. One of the first things that I noticed was that the wonderful "var" keyword and lambda expressions were not recognised. Obviously, the template generator was generating against the framework 2.0. I couldn't believe this was the only option we had available, especially with the release of VS2008. Google wasn't all that helpful and revealed nothing.

Looking at the "official" documentation also revealed very little, except that the using the template directive <@# template #> you could change the language from C# (the default) to VB. Fantastic. Not what I wanted, but I felt like it was the right place to begin my search.

So out came good’ol trusty Reflector and off I went, with my little code explorer hat on. After a few minutes of digging around I managed to track down this little bit of code:

string x = str.Substring(2);
if (StringComparer.OrdinalIgnoreCase.Compare(x, "v3.5") == 0)
    session.LanguageOptions["CompilerVersion"] = "v3.5";

Aha! Look at that... A quick change to the language parameter of the template directive and I was in business. :) So, should you want to compile your T4 template using all the 3.5 goodness that is on offer, use the following:
<@# template language="C#v3.5" #>
... or ...
<@# template language="VBv3.5" #>

And you should be in business... something I do think they need mention in the doc's somewhere.



No comments: