IsNothing? Definitely!

While reviewing some existing code at my new job I noticed that they use the VB.NET IsNothing() function instead of using the "Is Nothing" syntax. I didn't even know there was an "IsNothing" function so I compiled some code and checked it out with ILDASM. Here's what I compiled:

Public Sub Foo2()
    Dim o As AppDomain

    If IsNothing(O) Then
    End If
End Sub

At the resulting IL is:

.method public instance void  Foo2() cil managed
  // Code size       18 (0x12)
  .maxstack  1
  .locals init ([0] class [mscorlib]System.AppDomain o)
  IL_0000:  nop
  IL_0001:  ldloc.0
  IL_0002:  call       bool [Microsoft.VisualBasic]Microsoft.VisualBasic.Information::IsNothing(object)
  IL_0007:  brfalse.s  IL_000f
  IL_0009:  call       void [mscorlib]System.Diagnostics.Debugger::Break()
  IL_000e:  nop
  IL_000f:  nop
  IL_0010:  nop
  IL_0011:  ret
} // end of method Module1::Foo2

Ahhh... There's a call to the VisualBasic library. Let's see what Information.IsNothing does:

.method public static bool  IsNothing(object Expression) cil managed
  // Code size       5 (0x5)
  .maxstack  2
  .locals init (bool V_0)
  IL_0000:  ldarg.0
  IL_0001:  ldnull
  IL_0002:  ceq
  IL_0004:  ret
} // end of method Information::IsNothing

If your IL is a little rusty, allow me to translate it for you into VB.NET:

Public Shared Function IsNothing(ByVal Expression As Object) As Boolean
    Return (Expression Is Nothing)
End Function

Yup! A call to IsNothing() isn't inlined into a simple check for null. It's a function call. That will check for null. I was baffled when I found this. Why spend time developing such a method? Since this is Microsoft I assume there were functional designs, technical designs, code reviews, peer reviews, unit tests, etc... Just for a one-line function that could have very easily been inlined by the VB.NET compiler. I always assume when something seems so obviously wrong there must be something I'm missing...


  • It probably gets inlined by the JIT though.

    I think IsNothing is the VB.NET equivalent of the classic VB IsMissing function. It'd just make migration simpler...

  • It's a more consistant design: IsNull, Isumeric, IsDate, etc.

    You'd be surprised to find how many VB functions are inlined to their non-VB equiv. The VB compiler is pretty dang smart like that.

  • the VB.Net IsNothing is actually for compatibility with the VB6 IsNothing, not the IsMissing as dean suggested, IsMissing was used to test if optional parameters were specified or not.

  • I've found that IsNothing can be used to check nullable generics (system.nullable(of date) where Is Nullable will throw an error.

Comments have been disabled for this content.