.NET 3.5 Extension Methods

New to .NET 3.5 are a very powerful new paradigm called Extension Methods. Extension Methods, in a nutshell, are a way to extend the functionality of additional classes--adding new Methods to existing classes for the purpose of augmenting capability. The easiest way to demonstrate this is to show you a great example...

namespace ExtensionMethods
  public static class StringExtensionMethods
    public static bool IsNumeric(this string str)
        int i = int.Parse(str);
        return true;
      return false;

C#, as many of you know, lacks the built in VB.NET function, IsNumeric. (By the way, I can name a few things wrong with this particular extension method--so only use this example for the How-To of Extension Methods, not synthesizing IsNumeric) This extension Method extends the type string (the keyword "this" in the method signature is used to define what this method extends). With this newly written function, you can determine if a string is numeric by running code like this:

string s = "someValue";
bool bs = s.IsNumeric();
// bs is false;

string i = "7";
bool bi = i.IsNumeric();
// bi is true;

Now--as you may know, .NET strings do not intrinsically have a method IsNumeric() on them--this is our new Extension Method in action. In Visual Studio, you'll get intellisense if everything's set up right. Here's the rules you need to follow...

  1. All Extension Methods need to be defined in a static class
  2. All Extension Methods need to be defined as a static method.
  3. All Extension Methods need to take at least one parameter defined as follows:
    this (keyword) string (type) parameterName
    Where the type is whatever type that you wish to extend.
  4. The "this" parameter needs to be the first parameter. All other parameters are optional--and must follow "this".

Also I recommend the following points...

  1. Extension Methods adds complexity to your project and more importantly your IDE must parse these--don't go extension method crazy.
  2. Extension Methods should be extensions only. It's not advisable to define them in commonly used NameSpaces such as "System". That could be bad...
  3. If you're writing too many extension methods--maybe it's time to write a custom class that inherits from that data type, No?

A powerful tool, they are--extend the .NET framework they can. Enjoy them you must.

Also, technically, you can use 'em in .NET 2.0--but its a lot more work.


Zoidberg Away!

No comments: