Thursday, August 25, 2011

Macros in C#

Macros are a wonder feature found in C++. It allows you to write a template of sorts and use throughout. I bet you didn't know C# allows for templates too.

There is a wonderful template library built in to visual studio called T4. Just add a new file to your project and change the extension to ".tt"



<#@ template language="C#" #>
// This code was generated by a tool.
// Any changes made manually will be lost
// the next time this code is regenerated.
using System;

public class <#= this.ClassName #>
{
 public static void SayHello()
 {
 Console.WriteLine(”Hello World”);
 }
}
<#+
string ClassName = "MyClass";
#>

When you compile this will make a ".cs" file of the same name automatically. These templates are much more powerful than C macros. You have full access to any assemblies in the GAC (for example XML, Networking, and IO).

No comments:

Post a Comment