"Calling a method on null a reference" by Jon Skeet

Two months ago, I wrote a blog post called Extension Methods and null Objects. In this post, I described how to write Extension Methods in C# 3 and wrote a small sample code to add IsNullOrEmpty as an extension method to the String class. Well, guess what, I found that particular example in a book.

A few weeks ago, I bought Jon Skeet’s book C# in Depth, and have been reading it trough since then (I have to say that it is very well written and a pure joy to read, highly recommended if you are somewhat familiar with C# and would like to polish your knowledge of the language).

Reading part 10.2.4, "Calling a method on a null reference", I was surprised to discover that Jon used exactly the same example as I did! Well, I have to admit that it is I that used the same example as him, as it was already long printed when I wrote that post.

At first it seems odd to be able to call IsNullOrEmpty on a variable that is null without an exception being thrown, particularly if you’re familiar with it as a static method from .NET 2.0. In my view, code using the extension method is more easily understandable. For instance, if you read the expression if (name.IsNullOrEmpty()) out loud, it says exactly what it’s doing.

Nevertheless, I was very pleased with myself and, dare I say it, immediately thought "Great Minds Think Alike" :p.

Comments

One Response to “"Calling a method on null a reference" by Jon Skeet”

  1. Jon Skeet on January 18th, 2009 17:42

    I suspect I may well have seen it before I wrote the book, to be honest. It’s almost the canonical example of why it might sometimes be useful to be able to call a method on a null reference. If you do a search for “extension method” and “IsNullOrEmpty” there are quite a few hits :)

    Glad you’re enjoying the book though – do drop me a note if you have any feedback.

    Jon

Leave a Reply