T4 templates: Error on namespace

267 views Asked by At

I am trying to write a class in T4 template. It gives the error:

Compiling transofrmation: Type of namespace definition, or end-of-file expected

if I have the following code:

<#+
namespace Learn {
    public class Converter
    {

    }
}
#>

But it works fine if I remove namespace

<#+
    public class Converter
    {

    }
#>

My question is, why T4 doesn't recognize the namespace?

1

There are 1 answers

1
Frank On BEST ANSWER

<#+ #> is a class feature block. Anything you put inside this block will be written inside a class statement. When you add a namespace T4 will generate and try to compile something like this:

class MyT4TempGen {

     public string run() {
          inside here is code that uses a string builder to build up all your <# #> tags into one big statement
     }

     from here down all your <#+ #> tags are added

     namespace Learn {
        public class Converter {

        }
     } 

}

This is not valid C# code, namespaces can not exist within a class statement. When you do it without the namespace you will get this:

class MyT4TempGen {

     public string run() {
         inside here is code that uses a string builder to build up all your <# #> tags into one big statement
     }

     from here down all your <#+ #> tags are added         

     public class Converter {

     }

}

Which is valid c# code, your class will be a sub class of the one the T4 compiler creates.

Here is a link to the msdn docs that explain the supported tags. See the section "Class feature control blocks". Just remember that whatever you type into a tt or t4 file will be parsed and turned into .net code so you have to follow all the normal syntax rules.