skip to the main content area of this page
Patterns and Practices

 

Code Generation in Visual Studio Using T4 Templates - Screencast and Sample


Update July 27, 2008: Check out my own screencast, too: T4 Templates in Visual Studio for Code Generation Screencast

 

I have created and modified custom T4 Templates for the various software factories, like the Web Client Software Factory and the old Repository Factory, using the T4 Editor, but I didn't realize just how easy it is to use T4 in Visual Studio 2008 until I watched a screencast by Hilton Giesenow - How Do I: Create and Use T4 Templates.

If you are interested in trying out T4 yourself in Visual Studio, make sure you download and install the T4 Editor which will provide you a bit of intellisense while creating your code generation templates.

 

Quick T4 Template Sample

Create a new Visual Studio 2008 Console Application. Choose "Add New Item" and pick the Text File option. When naming the file, make sure you use the extension "tt". As you can see below, I added a text file and named in MyTemplate.tt. The MyTemplate.cs file is automatically created by Visual Studio.

 

Code Generation in Visual Studio 2008

 

Write some T4 Template Tags, which is basically inline ASP, in the MyTemplate.tt file as such:

 

<#@ template language="C#" #>
using System;
public class TestClass
{
    public void WriteToConsole()
    {
<#        for (int i = 0; i < 10; i++) { #>
        Console.WriteLine(<#= i.ToString() #>);
<#        } #>
    }
}

 

and when you save the file the following C# code gets generated automagically for you in the MyTemplate.cs file:

 

using System;
public class TestClass
{
    public void WriteToConsole()
    {
        Console.WriteLine(0);
        Console.WriteLine(1);
        Console.WriteLine(2);
        Console.WriteLine(3);
        Console.WriteLine(4);
        Console.WriteLine(5);
        Console.WriteLine(6);
        Console.WriteLine(7);
        Console.WriteLine(8);
        Console.WriteLine(9);
    }
}

 

In the Program.cs file just write code to run your generated code:

 

using System;
namespace ConsoleApplication5
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            new TestClass().WriteToConsole();
            Console.ReadLine();
        }
    }
}

 

And now you can run it to see your first use of T4 Templates in Visual Studio 2008 for code generation.

I can't think of a killer reason to use the T4 Templates for code generation in this way given the various code generators and O/R Mappers. However, it is always good to know we have the option.

Hope this helps,

David Hayden

 


Tags: T4


Topics



 

Popular Tags



Recent Links