Monday, October 12, 2009

Extension Methods in C#

Recently, I come across with the blog of Troelsen. He was mentioning that "Extension" methods in .NET 3.5 are good example of "Decorator Pattern". Here is the sample for extension method which satisfies the "Decorator Pattern" definition.

Decorator Pattern - Definition:

The decorator pattern provides a formal way to add new functionality to an existing type, without sub-classing. This will be useful when the class is sealed and classic inheritance will be not feasible to use.

Sample code:


public class TextMessage
{

string _message = string.Empty;
public string Message
{

get { return _message; }

set { _message = value; }

}

public void Display()
{

Console.WriteLine("Here we go: " + _message);

}

}

public static class TextMessageExtensions
{
public static void DisplayWithHello(this TextMessage tm)
{

Console.WriteLine("Hello");

tm.Display();
}

public static void DisplayWithHi(this TextMessage tm)
{

Console.WriteLine("Hi");

tm.Display();

}

}

No comments:

Post a Comment