Tip 3 - How to get started with T4

So if you've been reading the Entity Framework Design Blog you will have heard us talk about T4. It is a technology that ships with Visual Studio 2008 (and 2005 as a separate download).

In .NET 4.0 the Entity Framework is leverage T4 to help with Code Generation and Model First scenarios.

In fact T4 is also being used in lots of other MS products now, including ASP.NET MVC and Dynamic Data.

So imagine you want to start using T4 now to get familiar with the technology now. How do you do that?

Its actually pretty simple. You can do some pretty useful things very easily:

  • Add a new text file to your project with the extension renamed to ".tt"

  • Drop some template code in the text file.

    <#@import namespace="System.Collections.Generic" #>
    <#
    Dictionary<string,Type> properties = new Dictionary<string,Type>();
    properties.Add("Age",typeof(int));
    properties.Add("Firstname", typeof(string));
    properties.Add("Surname", typeof(string));
    #>
    using System;

    public class <#="MyClass"#>{
    <# foreach(string name in properties.Keys) { #>
    public <#=properties[name].Name#> <#=name#>{
    get; set;
    }
    <# } #>
    }

    This template code, produces a class with a property for each Key in the dictionary called 'properties'. 

  • Save the ".tt" file. When you do this auto-magically a dependent ".cs" file will appear, that looks something like:

    using System;

    public class MyClass{
          public Int32 Age{
                get; set;
          }
          public String Firstname{
                get; set;
          }
          public String Surname{
                get; set;
          }
    }

As you can see T4 is very simple and should be pretty easy for people familiar with ASP.NET...

Give it a try.