Extension methods are available starting with C# 3.0 and Visual Basic 9.0, which were released in 2007 with version 3.5 of the .NET platform.
Let’s say I’m developing an application in which I am repeatedly required to perform a certain operation called “jazzing up” an integer. The operation multiplies the integer by five, and then subtracts one. The operation is required several hundred times in the code.
I could, of course, simply perform the calculation each time I come to it like this:
j = i * 5;
That works, but I don’t want to type it several hundred times, with 4 mistakes, and I suspect I will have to make several hundred code changes in the future when the “jazzing up” formula changes. So one solution is to develop a public static class which I’ll name “CMethods” that will contain a bunch of public static methods, and I’ll name one of those methods “JazzUp”.
The method will look like this:
public static int JazzUp(int i)
int j = i * 5;
Now, whenever I want to jazz up an integer, I can just call the static method like this:
j = CMethods.JazzUp(i);
That works, but I’ve got another idea. When I type a variable, followed by a period, intellisense pops up the available methods for that variable type. For an integer, I see methods like “Equals” and “ToString” and several others that are already built in and ready to use. It would be cool if I could add the “ZazzUp” method to that list.
Then I could jazz up an integer like this:
int j = i.JazzUp();
Well, this is what “extension methods” are. They are methods that you can spot weld or bolt on to the side of an existing type. Let’s change the JazzUp static method as follows:
public static int Jazzup(this int i)
int j = i * 5;
The method looks exactly like the previous method I wrote except I added a “this” modifier. Now the following statement works and intellisense pops up my “JazzUp” method for me:
int j = i.Jazzup();
Note that intellisense did not pop up all the methods in the CMethods class, only the method with the "this" modifier which pertain to the integer type.
If we can do this with primitive types like integers, can we also do the same with classes? The answer is, of course, yes, but why would we want to do this? If you wrote the class you want to extend, you could simply add a method and recompile, but what if someone else wrote the class? Well, you say, you could inherit from that class and extend that way, but what if the class is sealed? Obviously, then, extension methods have more use than simply extending primitive types. In fact, the truth is that extention methods (along with other language enhancements) were added to make developing LINQ easier. LINQ (Language Integrated Query) is basically a library of extension methods bolted to the side of the .NET framework, but that’s the subject of another article.