A Text Template Transformation Toolkit (or "T4") template is a text generation tool that mixes raw text and code to generate text as output.

Visual Studio contains tools to assist with the creation and execution of T4 templates.

To add a T4 template to your project, right-click on the project, and select Add | New Item from the context menu.

In the "Add New Item" dialog, the T4 templates are listed under the General category; but you can find them quickly by typing "T4" in the "Search Installed Templates" textbox.

There are two kinds of T4 templates: a Text Template and a Runtime Text Template. Each of these starts with a file with ".tt" extension, but is designed to generate at least one other file.

The Text Template regenerates the final output file every time you save the ".tt" file. This is a quick way to generate simple files, but it lacks flexibility.

The Runtime Text Template generates a VB or C# class that you can call from your code to generate the output file. We will focus on the Runtime Text Template in this article.

A Runtime Text Template consists of raw text (which will be exactly duplicated in the output file) and executable code, which the template will run. Any output of that code will be included in the output file. Code is delimited from the raw text by placing it between the <# and #> symbols. If you just want to output the results of an expression, you can surround that expression with the <#= and #> symbols.

For example, to output the current date and time, include the following line in your template.

<#=System.DateTime.Now #>

You can combine this with text as in the following example:

(This file was generated at <#=System.DateTime.Now #>!)

which would output something like the following:

(This file was generated at 06/25/2018 20:33:14!)

You can include more complex code between the <# and #> symbols, as in the following example:

for (System.Int32 I = 0; I < 5; I++)
	// WriteLine is a utility function that outputs text. 

The result of the above code is:


When you save a Runtime Text Template, Visual Studio generates code for a public .NET class with the same name as your tt file. You can instantiate this class as you would any other public class and call the TransformText() method to generate the output as a string.

For example, if I created a Runtime Text Template named "myT4Template.tt", the following code would generate the output and save it to a variable named "outputText".

var tt = new myT4Template();
string outputText = tt.TransformText();

T4 templates give you the flexibility to generate text and text files quickly and the flexibility to change the template without worrying about the associated data.