Thursday, October 2, 2008

Does C# need the Template pattern?

My understanding of the Template pattern is that it allows a programmer to provide a hook for outside use into a classes methods. With the advent of C# a new type has come into use, the Delegate. From the MSDN site
A delegate is a new type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value...


This sounds to me like a perfect candidate to hook into a method. Now maybe the Template pattern is still useful in other ways, although I haven't come up with one, but maybe Delegates can make it largely obsolete.

Some quick sample code I did to just test it out.

namespace DelegateTest
{
public delegate int Test(int MyInt);
class Program
{
public static Test MyTest;
static void Main(string[] args)
{
int SomeNumber = 5;
MyTest += new Test(MyInt);

if (MyTest != null)
{
SomeNumber = MyTest(SomeNumber);
}
Console.WriteLine(SomeNumber);
Console.Read();
}

public static int MyInt(int TestInt)
{
return 6;
}
}
}