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();
   System.Console.WriteLine(strIsNull);
}

Tagged: ,

§ One Response to Extension Methods on Null Instances

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

What’s this?

You are currently reading Extension Methods on Null Instances at JAWS.

meta

Follow

Get every new post delivered to your Inbox.

Join 1,015 other followers