A Surprising Fact About Extension Methods

Extension methods are awesome. They allow extending the API of an object by creating a static method that “attaches” to an instance of an object, provided the extension method targets that type, which can be a generic or non-generic class, or an interface. Did you know that Extension methods extend an instance of an object, and can be called even if the object is null? For instance, suppose we had an extension method:

public static class ObjectExtensions
{
   public bool IsNull(this object obj)
   {
      return obj == null;
   }
}

And can be called on an object:

object obj;
var isNull = obj.IsNull();

Behind the scenes, the .NET framework passes the reference to obj to the static IsNull method, which will be null.

This works great for chaining references to objects which may or may not exist. For instance, I like to write extensions for LINQ to XML, to chain drilling through a series of objects which may or may not exist. The following is the extension method:

public static class XmlExtensions
{
   public static XElement GetElement(XElement el, string childName)
   {
      if (el == null)
       return null;

      return el.Element(childName);
   }

   public static string GetElementValue(XElement el, string childName)
   {
      if (el == null)
        return null;

      return el.Value("childName");
   }
}

Using these extensions, you can drill through a large hierarchy. Whether the elements exist or not, the drill through code works because we handle null, and continue the null chain. If all the elements exist in the document, the value is returned. A sample of using this is below:

var doc = XDocument.Load("test.xml");
doc.Root.GetElement("Customer")
        .GetElement("LastOrder")
        .GetElement("Details")
        .GetElementValue("Cost");

If Customer, LastOrder, Details, or Cost elements are not in the XML, then a null is returned from GetElementValue. However, if all are provided, the cost is returned as a string. A simple extension can make working with hierarchical data much easier.

Advertisements

One thought on “A Surprising Fact About Extension Methods

  1. Pingback: Nulls and Extension Methods | Coding for Smarties

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s