Extension methods is a feature in C# 3.0 that allows for (pardon the circular definition) extending existing compiled types without having to edit the original source code. This allows us to add functionality to compiled classes (even in the Framework) without having access to the source code and having to recompile.
For a simple example, let's look at the System.String class. I have a set of utilities that I carry with me in almost every project that I work on, and in that I have a host of operators on strings to save me time. One static function is checking to see if a string ends with another string, regardless of case. The code itself is very simple, but still external to the string class. The whole reason to push this into a utility class is to save typing.
1: public bool StringEndsWithIgnoreCase(
2: string sourceString, string checkString)
4: return sourceString.EndsWith(
What if we could make this a method of the String class itself? Instead of calling:
1: bool endsWith = MyUltities.StringEndsWithIgnoreCase(string1, string2);
we could write:
1: bool endsWith = string1.EndsWithIgnoreCase(string2);
AND have the new method show in IntelliSense? With Extension Methods, we can!
To create an Extension Method, first create a static class (this is required). By default, then, all methods in that class also need to be static. Then, each extension method gets the first parameter decorated with the this keyword modifier. By rule, the "this" parameter must be first (if you have more than one parameter). The return type can be whatever you need it to be.
1: namespace Utilities
3: public static class StringExtensionMethods
5: public static bool EndsWithIgnoreCase(
6: this string stringIn, string checkString)
8: return stringIn.EndsWith(
To use this new extension method, you must have an include statement for your namespace that contains the extension methods. Once you've done that, you will have your new method appear in IntelliSense on all of your string variables.
As a side note, your extension methods can also be invoked statically in a stand-alone manner. To do this, pass in the instance variable that is being acted upon as the first parameter. In our simple example, the code would look like this:
1: bool endsWith = StringExtensionMethods.EndsWithIgnoreCase(string1,string2);
Care must be taken when naming extension methods for readability of the code. If I am extending an already existing function ("EndsWith"), I name my extension method with the same prefix so it is adjacent to the existing method in Intellisense, and obvious to the consumer what the function does.
In my next post we will examine a couple of useful extension methods on the ISession interface.