Code Generation and T4 Text Templates

In Visual Studio, a T4 text template is a mixture of text blocks and control logic that can generate a text file. The control logic is written as fragments of program code in Visual C# or Visual Basic. The generated file can be text of any kind, such as a Web page, or a resource file, or program source code in any language.

There are two kinds of T4 text templates:

Run time T4 text templates ('preprocessed' templates) are executed in your application to produce text strings, typically as part of its output.

Design-time T4 text templates are executed in Visual Studio to define part of the source code and other resources of your application.

Typically you would use several templates that read the data in a single input file or database, and generate some of your .cs, .vb, or other source files. Each template generates one file. They are executed within Visual Studio or MSBuild.

For example, your input data could be an XML file of configuration data. Whenever you edit the XML file during development, the text templates would regenerate part of the application code. One of the templates could resemble the following example:

As another example, the input could be a diagram of workflow in a business activity. When the users change their business workflow, or when you start work with new users who have a different workflow, it is easy to regenerate the code to fit the new model.

Design-time templates make it quicker and more reliable to change the configuration when the requirements change. Typically the input is defined in terms of business requirements, as in the workflow example. This makes it easier to discuss the changes with your users. Design-time templates are therefore a useful tool in an agile development process.

To create a design-time template, add a Text Template file to your project. Alternatively, you can add a plain text file and set its Custom Tool property to TextTemplatingFileGenerator.

The term model is sometimes used to describe data read by one or more templates. The model can be in any format, in any kind of file or database. It does not have to be a UML model or a Domain-Specific Language model. 'Model' just indicates that the data can be defined in terms of the business concepts, rather than resembling the code.

In any application that generates text files, precompiled text templates are an easy and reliable method of defining the text. However, this method cannot be used for text templates that change at run time.