While I was researching different ways of implementing a new feature for Gecortex Essentials 1.3, I came across an interesting problem. Basically, what I want to do was to add the same, new functionality to a number existing and possibly future classes. I don't want to modify these existing classes, and I also don't want to subclass each of these classes as that could prove to be quite onerous. I looked at a number of approaches.

There is a famous Gang of Four design pattern called the Decorator Pattern that is almost what I want. Essentially, Decorator allows you to “decorate” an existing class with new functionally without having to create a new subclass of that class. The nice thing about Decorator is that you can decorate a class with as many decorations as you want, without creating an unmanageable number of classes at the same time, This sounds promising but it is not entirely what I'm looking for. Decorator is most applicable when there are a lot of decorations and few classes to decorate. I have the opposite problem. I have lots of classes to decorate and only a few decorations.

Next, I looked at .NET Generics. I naively tried to declare a new template class as

class DecoratorClass<T> : T
  {
  public void NewCapability1()
  {
  }

  public void NewCapability2()
  {
  }
}

My idea was that if I wanted to add new functionality to an existing class, I would simply instantiate a new instance of that class as follows


DecoratorClass<ExistingClass> c = new
DecoratorClass<ExistingClass> ();

As it turns out, C# explicitly disallows a generic class from inheriting from its parameterized type and as such, this idea was dead before it began.

C# 3.0 has an interesting feature called Extension Methods that might be just what I'm looking for. In a nutshell, extension methods allow you to add new methods to an existing class without sub-classing, decorating or even recompiling the original class. To top it all off, it seems really easy to use as you can see from the following example.

public static class StringDecoration
{
  public static int ToInt32Ext(this string s)
  {
    return Int32.Parse(s);
  }
}

class Program
{
  static void Main(string[] args)
  {
    string s = "9";
    int i = s.ToInt32Ext();
  }
}

As you can see, strings now seem to have this new method called ToInt32Ext and all I had to do was declare a new static class and declare a single static method with a slightly modifed parameter list. What could be easier?

I still have a lot more work to do before I decide to use Extension Methods, but at the moment, I am pretty happy with the possibilities.