A number of articles I’ve read recently have mentioned “Extension methods” in passing, yet it is difficult to find out what this is, if you don’t already know.
A few searches, however, did turn up three good sources: MSDN provides this reference page, then I found a classic “Gu” blog post from March of ’07, and finally, the incredible Pete Brown tackles Extension methods as well.
This mini-tutorial will attempt to fill in the details and focus on two key uses of Extension Methods:
- To add functionality to a class you don’t own
- To enable method-based queries (using lambda expressions) in Linq
Adding Functionality to a Class You Don’t Own
Programmers are often faced with wishing that a given class had a method that the designer of the class did not supply. If the class is not sealed, you can derive a specialized version that has your method, but many framework classes are sealed. You can write around this problem, but it would be nice to create a method that looks like it is part of the original class, and Extension methods let you do just that.
Adding LastN to String
It is certainly possible to get the last n characters from a string, but it is a little tedious. The traditional way to do so (broken out into fragments so that the steps are obvious) is shown in this very small Silverlight application,
more here