Null Method Invocation

time to read 5 min | 948 words

About 6 months ago I left a comment here, and I returned now to check it, and found a real gem. Check this out, it is about invoking methods on null, like this:

Foo foo = null;
foo.DoWork();

 Wesner Moise explains what the possibilities are:

... An instance method can treat an null in special, default way to maintain continuity with nonnull objects and eliminate the need for callers to perform null checks. One example of this is how it simplifies the manipulation of binary trees. It's similar to the null object pattern, with the null object being null.

I can certainly think of several ways that this would be nice to use. It was removed from C# by the ECMA during the standardization process. It may be a good thing, I don't know if stuff like this are good (because they open up possibilities) or bad, because they mean more stuff to care about. Anyway, I'm not sure that I would ever want to see something like "if (this == null)" in my code any time soon.

One thing to note, this is supported by the CLR. C# will emit a callvirt IL call, which will cause a null reference exception, but this IL works just fine with no exceptions ( showing just the call, see the C# source below):

.method public hidebysig static void             Main        (string[] args) cil managed
{
      .entrypoint
      .maxstack 1
      .locals init ( TestNullMethodInvocation/Inner inner1, bool flag1)
      L_0000: nop     
      L_0001: ldnull
      L_0002: stloc.0
      L_0003: ldloc.0
      L_0004: call instance bool TestNullMethodInvocation/Inner::InstanceMethod()
      L_0009: stloc.1
      L_000a: ldloc.1
      L_000b: call void [mscorlib]System.Console::WriteLine(bool)
      L_0010: nop
      L_0011: ret
}

This translate to this C# call (except for the call vs. callvirt, of cours):

using System;
public class TestNullMethodInvocation
{
 public static void Main(string[] args)
 {
  Inner inner = null;
  bool result = inner.InstanceMethod();
  Console.WriteLine(result);
 }
 
 public class Inner
 {
  public bool InstanceMethod()
  {
   return true;
  }
 }
}