?

Log in

No account? Create an account
Gavin Greig [userpic]

Visual Studio's Best Kept Secret: T4

October 22nd, 2008 (01:03 pm)
current location: DD4 9FF

Beats me why Microsoft haven't made more of a fuss about this. It's obvious, if you use it, that Visual Studio contains a code generation system, but what's much less obvious is that there's support for writing your own code generation templates within Visual Studio - straight out of the box.

It's called Text Template Transformation Toolkit, or T4, it's been there since Visual Studio 2005, and you can code in it, using C# or Visual Basic, to produce virtually any text-based output you choose.  To see it in action, just create a new text file in your project, and give it the extension "tt". Underneath it, another file will appear that's the code generated by the template. It's regenerated whenever you save the template.

For a brief introduction, watch the first 20 minutes of Advanced code generation patterns with T4 & DSL Tools. The speaker, Oleg Sych, has a blog that's an indispensable reference. For an overview, including links to key topics in Oleg's blog, try Scott Hanselman. If you're serious about giving it a try, you will probably want to get the T4 Editor from Clarius. There's a freeware Community Edition and a paid-for Professional Edition.