The .NET framework is great, but most programmers find there are some useful features that are not accounted for in the framework. Many programmers I know create “helper” functions in each project to assist with this. Some people go so far as to carry around some portable source code (or compiled code!) to use in their projects. How many times have you recreated or used your own little “helpers,” “utility” or “tools” class in a  project?

I have found that in recent years (at least since widespread use of .NET 3.5), most of my universal “helper” functions are actually better implemented as extension methods. The ability to extend sealed classes is a feature that seems to have been overlooked by many programmers. This was introduced in .NET 3.5, so it’s unfortunately not available in .NET 2.0…  Perhaps yet another reason to upgrade your solutions!

Using extension methods is just a much more natural and convenient way to incorporate helper functions. Here’s an example… I really like using String.Format(), but I find it cumersome to to constantly type in “String.Format(blah, blah, blah)” when it could easily be an extension method.

Here it is in usual form:

string greeting = “Hello {0}!”;
string firstName = “Ben”;
string result = String.Format(greeting, firstName);

This is more smoothly represented as an extension method:

string greeting = “Hello {0}”;
string firstName = “Ben”;
string result = greeting.With(firstName);

Here’s the code to create the extension method “With.” All you need to do is add this code, and a “using MyExtensions” declaration:

namespace MyExtensions
{
 publicstaticclassMyExtensions
 {
  publicstaticstring With(thisstring format, paramsobject[] args)
  {
   returnstring.Format(format, args);
  }
 }
}

It’s so easy! All you have to do to add an extension method is create a public static method with “this <type> <name>” as the first argument. Doing that will extend the method universally for the specified type. You can even do this with the base class “Object,” exposing your extension for effectively everything, as the Object class is the “root” of the .NET type heirarchy. The vast number of derrived classes will automatically inherit your extension method.

Consider converting your own library of tools and utilities to extension methods! I’m sure like me you’ll be pleased to find it feels much more natural to use them as extensions.

Like this post? Share it!