.NET Extension Methods How-To

I had to learn the following simple steps for making an extensions method the hard way. You don’t have to.

Procedure

To write an extension method:

  1. Create a static class.
  2. Write a static method taking an object of the type being extended as first parameter.
  3. Add method parameters.
  4. Prepend the keyword this to this this parameter.
  5. Make the class and its extension method visible, by importing the namespace.
  6. Instead of calling the static method on the static class, call it on an instance of the type being extended. Skip the this parameter. The compiler will rewrite this and invoke the standard extension method instead.

Example

public static class MyExtensionClass { // Name not relevant.
  public static string AppendIndex(this string myString, int index) {
  return myString + index;
  }
}
  ...
  var s1 = "StringLiteral".AppendIndex(index);
  var s2 = myString.AppendIndex(0);
  var s3 = myMethodReturningString().AppendIndex(1);
  // And this can't work: string.AppendIndex(0);

Notes

  • The class does not have to be public. The method will be as visible as the class and the method access modifiers permit.
  • An extension method obviously does not have access to the non-public members of the type being extended.
  • Extension methods only work on instances. (You’ll need a string instance to access the extension method in the example.)
  • What’s so nice about this? It’s the ability to learn what you can do with an object via IntelliSense, without browsing around like crazy or exercising the IDE’s ability to Find in Files.

Post a Comment

You must be logged in to post a comment.