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

Comments on this post: Null Object pattern

# re: Null Object pattern
Requesting Gravatar...
How is this better than:

Debug.WriteLine(x == null);


What does your extension method give us that we don't already have?

Also, this allows you to check for null on value types, such as int


Which always returns false. Returning false is good in this case because value types are never null, but does it make sense to be able to check for null on a value type?

This extension method doesn't really give you much at all, and hence personally I would prefer the normal "x == null" check instead.

Cheers :)
Left by OJ on May 26, 2008 5:59 PM

# re: Null Object pattern
Requesting Gravatar...
agree with OJ,

The idea of having to write the null checking code your self isn't solve the problem either i use the extension method you wrote or just check with x==null dosn't matter.

won't give me much of benfit, it would be solved if i can write obj.ShowMessage and obj is null, and have null as a return value insted of exception.
Left by Adel on May 26, 2008 8:08 PM

# re: Null Object pattern
Requesting Gravatar...
OJ and Adel: You both have good points. There is no difference between Debug.WriteLine(x == null) and Debug.WriteLine(x.IsNull()), but that wasn't the point of the example. The use of the Debug.WriteLine statements was to easily show that the extension method behaves correctly and doesn't cause a NullReferenceException.

The issue shown by Debug.WriteLine(10.IsNull()) can easily be solved by making the extension method generic and constraining the type parameter to be a class. That causes your Debug.WriteLine(10.IsNull()) to generate a compiler error.

For the most part, this syntax is no different than testing "x == null" other than introducing a consistent pattern (yes, I know that "x == null" is itself a consistent pattern). However, it also starts to introduce the concept of treating nulls and nullability as a first-class language citizen.

Adel, you are correct in that this extension method won't solve the problem of obj.ShowMessage if obj is null...that's the whole point of the real Null Object pattern and treating null as a first-class citizen. The only way that will be solved is for Microsoft to introduce changes in the runtime.

In the meantime, this is simply another alternative which, in my opinion (and it is only my opinion, which is neither a mandate nor a recommendation), is a bit clearer and more concise.
Left by Scott on May 26, 2008 8:27 PM

# re: Null Object pattern
Requesting Gravatar...
The extension method is much more elegant and easier to read if nothing else.
Left by RickE on May 27, 2008 9:50 AM

# re: Null Object pattern
Requesting Gravatar...
I used the null object pattern in a project of mine and I have to recommend against its use. Instead of obvious failures we simply ended up with mysterious failures. Sure we saved the program from crashing in certain cases, but crashes are a good thing when you worry about the integrity of your program.

I also believe the extension method is a little silly. In addition to it encoding no useful information, using it habitually will circumvent some safety mechanisms in the C# compiler. Consider:

int foo = 5;
Console.WriteLine(foo == null); // Warning, expression is never false.
Console.WriteLine(foo.IsNull()); // No warning!

That is, of course, unless you add the 'class' generic type constraint to your extension method.
Left by Chris Faulhaber on Jun 01, 2008 8:12 PM

# re: Null Object pattern
Requesting Gravatar...
Chris, in my earlier comment I address the issue of simply extending object since it does then allow the extension method to be applied to built-in types like int. The change is to add a class constraint, as you mention.

I agree that you should always worry about the integrity of your program, but do not agree that crashes "are a good thing". The more correct approach is to adopt a defensive style of programming where you actively check for situations that could cause an exception and take a different course of action. The best example of this is using the "as" operator.

Consider this code:

SomeClass c = new SomeClass();
IDisposable id = c as IDisposable;

The call to id.Dispose() will always throw a null reference exception if SomeClass doesn't implement IDisposable since the "as" will return null.

The defensive way to do this would be:

SomeClass c = new SomeClass();
IDisposable id = c as IDisposable;
if (id != null) {

or, using the extension method:

SomeClass c = new SomeClass();
IDisposable id = c as IDisposable;
if (!id.IsNull()) {

Yes, the two if statements are effectively identical. The only real difference is that the extension method introduces a level of consistency in the way the test is performed and allows for other more readable syntax as well (consider an equivalent IsNotNull() extension, which would probably have been the better extension method to write anyway).
Left by Scott on Jun 01, 2008 11:02 PM

# re: Null Object pattern
Requesting Gravatar...
That's what I get for failing to read the other comments =).

I suppose my view of defensive coding is a bit different than yours. Were anything essential to happen in the SomeClass disposer (for example, say the calling code believed it held some unmanaged resource that is now held elsewhere), I very much prefer an immediate crash with an InvalidCastException to the gradual exhaustion of that resource. Failing as early as possible (in the form of a crash) is a defense against the unpredicted state of the program causing integrity issues.
Left by Chris Faulhaber on Jun 02, 2008 9:29 AM

# re: Null Object pattern
Requesting Gravatar...
No worries. I won't hold it against you this time. :)

It does sound like our views on what defensive programming is are different. In the particular case of a Dispose method, it should almost never throw exceptions.

That being said, the example I showed would not have caused an InvalidCastException since the "as" operator will always succeed. It may not actually perform the cast, in which case it will return null. So, the code would have thrown a NullReferenceException, but only when the call to id.Dispose() is executed. I see code written this way a lot, where objects are cast to other objects using the "as" operator and the result is never's just assumed that the cast will always succeed and result in a valid (non-null) object.
Left by Scott on Jun 02, 2008 9:39 AM

# re: Null Object pattern
Requesting Gravatar...
I would agree with Chris that "Failing as early as possible (in the form of a crash) is a defense against the unpredicted state of the program causing integrity issues." I think that for really complicated application, defense by adding "if" statements leads to overcomplicated/unmanageable code. That's why exceptions were added... It is better and safer to let exceptions to raise and to propagate up to the level (if any), which has a knowledge of how to handle them. But sure, we don't want exceptions in Dispose(), so "if" here is a good thing.
Left by Vladimir Kelman on Jul 02, 2008 11:23 PM

# re: Null Object pattern
Requesting Gravatar...
Vladimir, I still maintain that failing early by crashing is not defensive programming. Defensive programming is ensuring that in those places you know something might fail you take steps to ensure that it doesn't or at least if it does you don't crash.

A good example of this is in casting. There are 2 ways you can cast:

string x = (string)someVariable;
string x = someVariable as String;

In both of these cases executing a method on x immediately after the cast may fail if someVariable is not actually castable as a string. This is a case that can be handled without throwing an exception by using the "is" operator or by testing to see if x == null after the "someVariable as String" call.

For "really complicated programs" you don't want to have them crashing on simple things. Remember that catching exceptions is expensive and if an exception is thrown it will always be just might be caught all the way at the top of your application stack and display the "standard" .NET exception dialog, which isn't friendly nor useful to the end-user.

Yes, it is better to let exception propogate to a level that knows how to handle them, but, again, that isn't defensive programming but rather exception management.
Left by Scott on Jul 04, 2008 8:42 AM

# re: Null Object pattern
Requesting Gravatar...
I believe only .NET provides these types of extensions, but if I were to implement it in Java, the isNull method would get duplicated in each and every other class(And inheritence I would not prefer). So I would prefer to go with if(x==null) conditions in my app.
Plz share your thoughts on this.
Left by Ram on Sep 12, 2012 10:45 AM

Your comment:
 (will show your gravatar)

Copyright © Scott Dorman | Powered by: | Join free