← Back to list

Best practices for working with T4 Templates in Visual Studio

Hi, I’m Tim. I’ve been working with T4 templates a lot in the past and even developed some Visual Studio extensions to improve the…

Tim Maes · 2024-01-11 12:44 · 7 claps · 2.8 min read
#4t #template #code-generation #visual-studio #csharp
Open on Medium ↗

Best practices for working with T4 Templates in Visual Studio

Hi, I’m Tim. I’ve been working with T4 templates a lot in the past and even developed some Visual Studio extensions to improve the experience and productivity when working with T4 templates in Visual Studio. In the world of .NET development, T4 (Text Template Transformation Toolkit) templates are a powerful tool for generating C# code. In this blog post, I’ll share some best practices for setting up and using T4 templates effectively in your projects.

I assume you have a basic knowledge of what T4 templates are and how they work, for the basics I would refer you to the official documentation.

T4 setup and structure

Always start your T4 template file with a comment indicating that it is auto-generated. This serves as a crucial reminder that any manual changes made to the generated code will be overwritten the next time the template is executed. For instance, you can add:

// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a T4 template.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
<#
...
#>

Using .ttinclude for file modularity

To keep your T4 templates maintainable, use .ttinclude files. These files allow you to extract and reuse common code across multiple templates. This not only keeps individual T4 files small but also promotes separation of concerns. For instance, you can have a .ttinclude file for common classes and methods used across different templates.

Create the example.ttinclude file

<#@ template language="C#" #>
<#@ assembly name="System.Configuration" #>
<#@ import namespace="System.Configuration" #>

<#+
    public string GetString()
    {
        return "Hello T4";
    }
#>

Use it in your .tt file

<#@ template language="C#" #>
<#@ include file="example.ttinclude" #>

<#
    string value = GetString();
#>

Example in solution explorer

Example in solution explorer

Benefits

  • Reusability: You can include example.ttinclude in any T4 template in your project that needs classes and methods defined.
  • Maintainability: All templates including it will automatically use the updated logic if you apply changes.
  • Organization: Keeps your T4 templates clean and focused on their specific tasks, while common functionality is abstracted into .ttinclude files

Organizing Output

Instead of generating multiple child nodes under the T4 file, configure your T4 template to write the generated files directly to a specified destination. This approach enhances the readability of your solution structure and makes it easier to navigate and manage the generated files.

To achieve this, you can try the following steps:

Add the following method to in your T4 template, or in a shared .ttinclude file if you want to reuse it

<#
public void SaveFile(string folder, string fileName, string content)
{
    using (FileStream fs = new FileStream(Path.Combine(folder, fileName), FileMode.Create))
    {  
        using (StreamWriter str = new StreamWriter(fs))
        {
        str.WriteLine(content);
        str.Flush();
        }
    }
}
#>

In your T4 template, write the generated output to a folder using the SaveFile method:

<#
SaveFile(folder, filename + ".cs", this.GenerationEnvironment.ToString());
this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
#>

What happens here is, we get the generated code from this.GenerationEnvironment, and after we write our file, we remove it so that not output is generated by the T4 template.

Benefits

  • By doing this you can write classes to the correct folder or project.
  • Prevents one big list of nested nodes under your .tt file

Keep in mind, by default the engine will still generate an empty node under your .tt file.

Tools and Extensions for Visual Studio

The .net community has created some useful tools to work with T4 templates.

VS Editors

By default, Visual Studio has no intellisense or syntax highlighting for T4 templates. It can be hard to write or maintain a template, but there are some extensions that provide basic colorization or intellisense.

T4 management

I developed an extension called T4Executer which allows you to attach the execution of T4 templates to build events. You can specify what templates to run before your project builds, during or after build. You can also specify what templates to ignore, for example .ttincludes.

T4Manager has some useful utilities to help to manage your T4 templates in your solution. A great tool to have control over what files are generated.


메타데이터
post_id
09eed730af1e
slug
best-practices-for-working-with-t4-templates-in-visual-studio-09eed730af1e
url
https://medium.com/@timmaes/best-practices-for-working-with-t4-templates-in-visual-studio-09eed730af1e
canonical_url
https://medium.com/@timmaes/best-practices-for-working-with-t4-templates-in-visual-studio-09eed730af1e
author_url
https://medium.com/@timmaes
status
ok
fetched_at
2026-06-28 10:39:35