Share on reddit
[`google_buzz` not found]
Bookmark this on Digg
Share on StumbleUpon

INTRODUCTION: The Gang of Four were pretty smart folks. They gave us a lot of design patterns to use to make better application architectures. One of the patterns they gave us was the Facade, which is generally used to provide common functionality for objects that don’t necessarily have a polymorphic purpose for the object. In C# we use static classes to build facades, which is great. Facade classes allow you to group together similar functionality and because the classes and methods are static, there is an expectation that they should work on any instance of the object(s) being manipulated.

Extension methods take the Facade one step further. Instead of having to reference a Facade class specifically, the extension methods bring the facade methods right to the class(es) they apply to. You might be asking right now, “What is an extension method?” Extension methods are defined as static methods of static classes that receive the context of a single object instance that allows you to present the functionality of the method as an extension of the object.

EXAMPLE

public static class MyExtensionFacade
{
    // Normal facade implementation
    public static void IncrementInt32ByDecimal(out int source, decimal value)
    {
        source += (int)(value + 0.5m);
    }

    // Extension Method
    // Notice the use of the this keyword, it defines the object that the
    // extension method works on.
    public static void IncrementByDecimal(this int source, decimal value)
    {
        IncrementInt32ByDecimal(out source, value);
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        int i = 10;
        decimal d = 15.75m;

        // Call facade method as normal.
        MyExtensionFacade.IncrementInt32ByDecimal(out i, d);

        Console.WriteLine($"i = {i}");

        // Call as extension method
        i.IncrementByDecimal(d);

        Console.WriteLine($"i = {i}");
    }
}

CONCLUSION: As you can see from the example, the extension method is much simpler to call and makes your code cleaner. As a matter of fact, the entire LINQ framework is a series of extension methods. They can be a very valuable and powerful arrow in your quiver of Ninja tricks.