Why Extension Methods?

Extension Methods, introduced in the C#3.0, provide a way to add a method to an existing type without having access to the source code of that type.

Although Extension Methods were added to support LINQ (a MOST awesome innovation) if you use generics (introduced in C#2.0) to create strongly typed collections and find yourself storing these strongly typed collections as strings in a file then Extension Methods provide a very natural way to extend the strongly typed collection.

For example, take List<MyCustomClass>.  If this gets stored in a file, say as name=value pairs, then it would be great to be able to parse the contents of that file simply by calling List<MyCustomClass>.Parse(fileContentsAsString).

Unfortunately, unless you’re at Microsoft (or Novell ala Mono) you probably don’t have the source code to the generic List type.  Even if you do have access to the source code you can’t anticipate all of the specific types users will create or the way they will represent them as a strings.

Enter Extension Methods.  They provide a way to extend List<MyCustomClass> (and, more generally, any type including generic types like List<T>).  So you can add a Parse(string) method to go from string form to List<MyCustomClass> form.  You can also add a ToString() method to go from a List<MyCustomClass> to a string.

The only peculiarity I’ve found so far is that the Extension Method must be invoked on an instance of the type even though they’re defined as static methods of a static class.  Not sure why the language designers chose to go this way but I’m sure there’s guidance on this out there somewhere.

No comments:

Post a Comment