Geeks With Blogs


Microsoft Store

Support This Site

AddThis Social Bookmark Button

Locations of visitors to this page

Subscribers to this feed

TwitterCounter for @sdorman

Creative Commons License

Scott Dorman Microsoft MVP, Software Architect, Developer, Author

I've been trying to catch up on my reading and came across this post by Fredrik Normén where he raises the question about returning null or using the Null Object pattern. Interestingly enough, last month while I was in Seattle for the 2008 MVP Summit I had a very similar discussion. The end result of that discussion was that null objects, and nullability in general, ideally should be treated as a "first-class" citizen in the CLR. This means that if you try to execute a method on a null object you get a null back in return rather than a NullReferenceException.

I tend to follow a very similar philosophy as Fredrik in that I return null in some circumstances and empty collections (or other appropriate defaults) in others. I think this style has grown from the fact that nullability has never been a first class citizen in most programming languages.

A few of the comments suggested the use of an extension method to accomplish Fredrik's idea of an "IsNull" property. Since we only have the ability to create extension methods, I created an extension method called IsNull that extends Object Class (System) to see if this would work.

This is, perhaps, the simplest extension method I've seen and worked with. The extension method is:

   1: public static class NullObjectExtenstions
   2: {
   3:     public static bool IsNull(this object source)
   4:     {
   5:         return (source == null);
   6:     }
   7: }

Using this extension method is also just as easy. Here is a simple console application I wrote to verify that this does indeed work:

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         string x = null;
   6:         List<string> y = null;
   7:         CultureInfo culture = null;
  10:         Debug.WriteLine(x.IsNull());
  11:         Debug.WriteLine(y.IsNull());
  12:         Debug.WriteLine(culture.IsNull());
  14:         if (!culture.IsNull())
  15:         {
  16:             Debug.WriteLine(culture.DisplayName);
  17:         }
  18:     }
  19: }

The output of this application is:


The last call to Debug.WriteLine(culture.DisplayName) is never executed since culture.IsNull() returns true so we don't hit the NullReferenceException.

Posted on Sunday, May 25, 2008 6:28 PM .NET (General) , .NET (C#) | Back to top

Copyright © Scott Dorman | Powered by: