Extension Methods on Null Instances

6 January, 2009 § 1 Comment

I was reading some blog posts and came across one from Brad Wilson about a year ago. Extension methods are a pretty cool construct, allowing you to add instance methods to sealed classes easily. This brings with it a way to write code that can cause some weird readability issues. Often used is the static method String.IsNullOrEmpty. With an extension method you could add that method to instances and the code will work fine, even if the object is null.

Here’s a code sample:

using System;

public static class MyExtensions
   public static bool IsNullOrEmpty(this string str)
      return String.IsNullOrEmpty(str);

Now all Strings will have a method to check if they are null or empty. You can see that the readability would make you think that a NullReferenceException would be thrown if the object is null and the method wouldn’t get called. This is the odd part of extension methods.

The method will still get called, and the code will work like normal.

public static void Main()
   string str = null;
   bool strIsNull = str.IsNullOrEmpty();

Where Am I?

You are currently browsing entries tagged with extension methods at JAWS.