C# 3.0 Extension Methods and Null Instances
C# 3.0 has a feature that allows you to extend an existing class, even one you didn't write. The extensions allow you to add instance methods (sorry, static methods not supported) to any class.
What I wasn't sure was whether or not you could call these extension methods when you have a null instance of the object, since they're instance methods. The C++ guy in me said "sure, that should be legal", and the C# guy in me said "it's probably illegal, and that's too bad". Amazingly, the C++ guy in me won!
This code executes perfectly:
using System;
public static class MyExtensions {
public static bool IsNull(this object @object) {
return @object == null;
}
}
public class MainClass {
public static void Main() {
object obj1 = new object();
Console.WriteLine(obj1.IsNull());
object obj2 = null;
Console.WriteLine(obj2.IsNull());
}
}
When you run it, it prints out "False" and "True". Excellent!

I think if you look at the the implementation of the extension method, it makes sense why it works. I hope it doesn't lead to confusion for new programmers as to why sometimes (in their view) you can call methods on a null instance and other times you cannot.
Posted by: Rob Cannon | January 12, 2008 at 10:39
Yeah, you'd think that C# would throw an exception rather than allow the parameter to be null. We ended up using the feature to create a null-propagating extension method:
http://code.logos.com/blog/2008/01/nullpropagating_extension_meth.html
Posted by: Ed Ball | January 14, 2008 at 08:44
Just to clarify on the static issue: it is true that you cannot add static methods to a class using Extension Methods, but you can use Extension Methods in a static fashion by passing the variable as the first parameter. This example should also work:
object obj1 = new object();
Console.WriteLine(MyExtensions.IsNull(obj1));
object obj2 = null;
Console.WriteLine(MyExtensions.IsNull(obj2));
Don't get me wrong, I do not see a lot of value in this approach, but it will work.
Personally, I think Extension Methods are the best new C# feature. Here is a link to my article on Extension Methods:
http://www.developingfor.net/c-30/upgrade-your-c-skills-part-1-extension-methods.html
The reason the Null objects work is because behind the scenes the static method is actually being called. I hate the phrase "syntactic sugar", but that's all the EMs really are in the end. So, just like you could pass a Null to the static method, you can call the EM on a Null object.
Good Stuff Brad!
Joel Cochran
http://www.developingfor.net
Posted by: Joel | January 23, 2008 at 18:38
Hi Brad,
The ability to use extension methods on null references allows for some interesting API possibilities. I wrote about one potential API awhile back:
http://diditwith.net/2006/10/24/NeatTricksWithExtensionMethods.aspx
Posted by: Dustin Campbell | February 01, 2008 at 08:46