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
3: public static bool IsNull(this object source)
5: return (source == null);
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
3: static void Main(string args)
5: string x = null;
6: List<string> y = null;
7: CultureInfo culture = null;
14: if (!culture.IsNull())
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.