T4 Code Generation with Visual Studio 2010

DZone 's Guide to

T4 Code Generation with Visual Studio 2010

· ·
Free Resource

T4 (Text Template Transformation Toolkit) is a code generation system that has been around for a while, bit is a little bit more accessible with Visual Studio 2010.  It allows you to quickly generate code for your application and it is used in several places behind the scenes in Visual Studio.  It can be a very powerful tool when you have code that needs to be reused but also configured at the same time.  I have a CodePlex project that is a T4 template to generate a data layer for the ADO.NET Entity Framework if you would like a more advanced sample.  You can find it at http://efrepository.codeplex.com.

To get started, add a new item to your project and select "Text Template".  You will get a dialog to set the name with a .tt extension.  I'll use "TestTemplate.tt" for this example.  The newly created file will have the following text:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".txt" #

Notice that the language is set to C# and the output extension is ".txt".  The default file name that gets generated will be the file name of the template itself plus the output extension.  In this case the generated file would be called "TestTemplate.txt". If we change the output extension to ".cs", the file would be "TestTemplate.cs".

You can use really any C# code you want inside this file to generate your code.  If we add text to the file it will get written to the output file and any code blocks you enter will be evaluated when the template gets processed.  With a little work, you can get some really cool results. 

Code blocks are delineated with "<# #>" and the overall structure resembles ASP.NET.  You can import namespaces and even use include files.  Below is a couple of lines from my efrepository T4 tem

<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ import namespace="System.IO" #>

The include files are also T4 templates and the namespace you can use are standard .NET namespaces. They can be custom code or framework libraries.

You can also specify methods within your template that can be called from the template itself.  Methods must be surrounded by a "<#+" block:

string DoSomething(string param)
// Do something and return a string

The templates are also relatively easy to read, so it's not too hard to figure out what someone is doing if you are looking at one already created. T4 is very powerful and when you get the hang of it, it can really make things easy when doing code generation.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}