Generating Code using T4 Text Template in .NET Framework

 Automatic code generation is a emerging field in computer science where you will be able to generate the code which otherwise would have to be manually written by a software developer. Here we are going to discuss about basic tool from Microsoft known as T4 Text Template.

There are many advanced code generation tools which uses latest technology such as AI to understand the user requirement and generate the piece of code based on a requirement.

What is T4 Text Template?

Here we are going to discuss about a simple tool which is less heard about in code generation space, known as T4 Template from Microsoft. Its a Open source toolkit for template based code generation. Source file has an extension ending with tt.

Where T4 Text Template can be used?

This would be helpful in cases where there is a requirement of large number of classes and properties to be generated, if we are manually going about coding these classes it would be tiring and will be prone to more errors. Here we will see a simple .NET class generated using the T4 template framework.

Demo

For this exercise we can create a console application in .NET framework and add Text template items to the project which would act as the template for generating the code. Text template items can be found in Visual studio project -> Add new Item Dialog as shown below:

T4 Text template


Once the template file is created we can add the necessary schema/structure of our class to the template file as shown in the figure below:

Template file in T4 Template


As shown in the figure this creates a output file of type ".cs" as  mentioned in the directive statement at line number 3. We are going to generate a Product class in the namespace ProductInfo which will contain different properties related to the Product.

The code written inside the <# -- #> statement is called the standard control block which is a pure c# code. Here I am storing the property information in a list for the demo purpose. In actual use case this information will be specified in some xml file or JSON file where the user provides inputs. 

Once the property information is retrieved we use expression blocks to evaluate the expression and convert that to string as shown in line number 22, which is identified by <#= --- #> statements.

Once the file is saved file will be auto generated in the code behind as shown in the figure below:

Auto generated code

Content of ProductTemplate.cs is as shown in the figure below:

Auto Generated .NET code


Comments

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Mastering Concurrency with Latches and Barriers in C++20: A Practical Guide for Students

Graph Visualization using MSAGL with Examples