.Net Extension Methods

Extension Methods – What are they?

They are methods written by you which allow you to extend classes that you cannot modify directly.  These might be classes you’re using from a third party DLL, or maybe you work in an organisation where your business objects are untouchable by a lowly developer such as yourself (and me), or maybe you just want to add some extra functionality to the String class.  If any of these situations ring true then extension methods are something you should know about.

How do they work?

In order to start using extension methods within your code you need to (at the very least) create yourself a static class to store them in.

public static class MyExtensionMethods
{
}

Then just add a static method to it as you would to a normal static class with one tiny addition, the use of the keyword this before the first parameter.

public static class MyExtensionMethods
{
   public static bool MyExtensionMethod(this string value)
   {
      // TODO write my extension method
   }
}

The this keyword marks the MyExtensionMethod as an extension method and the parameter type immediately after the keyword tells .NET which class the extension method is to be applied to, which in this case is the string class.

You then just write your method and interact with your parameter as normal but then when you come to use the class you’ve just extended you’ll see the extension method available in the intellisense list.

Example

Okay, time for an attempt at a real world example. For some reason I’ve settled on a baby naming application for this but please bear with me.

So, let’s assume you’re working on this baby naming application and that you’re working with a third party DLL called Names which exposes the methods IsBoysName(), IsGirlsName() and IsBoyAndGirlsName() via a class called Name, and that your boss is adamant that there has to be a method that confirms if the name entered by the user is a palindrome or not. This is a er perfect example of where an extension method could help out.

(NOTE: Yes, admittedly there are other ways of achieving this outcome such as creating your own class which inherits from the Name class but I think using an extension method is neater and reduces a lot of potential overhead)

Here’s how to satisfy your boss (by the way, I’ve included a sample application containing this code at the bottom of this post):

public static class MyExtensionMethods
{
    // The keyword this tells .NET that I want to extend the Name class
    public static bool IsPalindrome(this Name nameToCheck)
    {
        // Code to check if the Value property of the Name object
        // is a palindrome
        char[] charArray = nameToCheck.Value.ToCharArray();
        Array.Reverse(charArray);
        string reverseValue = new string(charArray);

        if (string.Compare(nameToCheck.Value, reverseValue) == 0)
            return true;
        else
            return false;
    }
}

And that’s it. Super simple but really useful.

Now if I go to use an instance of the Name class in my code I can see the IsPalindrome extension method is available to me from the intellisense menu:

IsPalindrome

Happy coding.

Download Code Example