Understanding T4: <#@ import #> directive


Here is how MSDN documentation defines the import directive.

By using the import directive, you can refer to types in a text template without providing a fully qualified name.

Here is what happens under the hood.

Template

<#@ template language="C#" debug="True" #>
<#@ import namespace="System.Diagnostics" #>
<#
    Debugger.Break();
#>

Compiled Template

using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TextTemplating;  

namespace Microsoft.VisualStudio.TextTemplating559506E3E78F9B3E7
{
    public class GeneratedTextTransformation: TextTransformation
    {
        public override string TransformText()
        {
            Debugger.Break();
            return this.GenerationEnvironment.ToString();
        }
    }
}

Notice that T4 transformed the import directive into a C# using directive in the compiled template. That allowed us to reference System.Diagnostics.Debugger class in the template code without specifying its namespace.

About T4

T4 (Text Template Transformation Toolkit) is a template-based code generation engine. It is available in Visual Studio 2008 and as a download in DSL and GAT toolkits for Visual Studio 2005. T4 engine allows you to use ASP.NET-like template syntax to generate C#, T-SQL, XML or any other text files.

Ready for more? Read about <#@ assembly #> directive or go back to the overview.

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
Understanding T4: <#@ assembly #> directive
Understanding T4: <#@ output #> directive

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!