.NET 3.5: Extension Methods

4:32 pm programming

Extension methods are static methods that, through the magic of the compiler and Visual Studio’s IntelliSense, can be made to appear as if they’re actually members of a particular type. The key is that the target type can be any type, including the standard .NET types. Thus, if you want to add features to a 3rd-party class, you don’t have to resort to Booch utilities.

public static class MyExtension {
  public static String prefixWith(this String target, String prefix ){
    return prefix + target;
  }
}

String result = "foo".prefixWith("bar");

This is a decent feature, although I have two concerns:

  1. There’s potential for developer confusion, especially with developers reading unfamiliar code. “prefixWith()” isn’t a standard known method of String so you’re going to be thrown for a bit of a loop when you see it. Ordinary static methods at least have a big class name attached to them so it’s obvious when you’re using nonstandard code.
  2. I’m yet not sure how extension methods avoid name collision, but it’s bound to become an issue. All you have to do to attach an extension method on potentially every type in the system is to import the namespace of a class that defines the extension method. That can get out of hand quickly.

Lastly, there’s one cool feature with extension methods: since they’re just syntactic sugar for a static method, they don’t require an actual instance in order to “use them on a reference”. So I could have:

public static class MyExtension {
  public static bool isNull(Object o ){
    return o == null;
  }
}

String foo = null;
return foo.isNull();

By the way, that sound you hear is the Ruby enthusiasts snickering.

One Response

  1. Ted Says:

    Bah, beat me to it! :-D

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.