Oleg Sych has a great set of posts that show how to use the T4 Templating feature that is included in Visual Studio 2008. This is a great technology that makes it really easy to create code generation capabilities inside a project. He goes into the details, but it’s really simple to get started.

  1. Add a text file with a “.tt” extension.
  2. Add your template to the file.
  3. Add logic to the template in your language of choice (VB.NET / C#)
  4. Save the template to have it spit out the generated code.

It’s really easy to do and VS will automatically generate the code each time you save the .tt template.

There are some free add-ins available that give a nice experience when writing the T4 templates. The tools from Clarius Consulting give intellisense support for the T4 syntax. They also do syntax highlighting on the template.

You can even debug the T4 templates using Visual Studio! Gareth Jones has a post that describes how this works.

So, next time you’re writing some painful, repetitive code / xml / sql / etc, remember that you can use the T4 capabilities to make things much easier and faster!