Saturday, 19 December 2009

vb.net nothing not the same as null

A colleague of ours (Paul) noticed this behaviour in vb recently:

Dim s as string = string.empty
If ( s = nothing ) then
   ' Do something
End if
The condition was met whether s was nothing or empty!

Paul also mentioned that changing the condition to:
If ( s is nothing ) then 
   ' Do something
End if
Which worked as expected - would pass for a null string and fail for an empty string.

We also discussed use of:
IsNullOrEmpty()

...which is a much more convenient method of checking for nothing and empty.

Another colleague Simon noted that he usually uses the (hangover from vb6)
Len()
...function which exhibits the same behaviour as is-null-or-empty!

A bit of digging with reflector and a look at the IL turned up some surprising facts (if the reflected code is to be trusted).

The statement
If ( s = nothing ) Then '(where s is a variable of type string)
End If 
...emits as:
VisualBasic.CompilerServices.Operators::CompareString() 
...Whereas the statement

If (s is nothing) Then
End If
...emits as: ceq – compare equal instruction

Already it’s clear that the “is nothing” statement is preferable in this context (and not just because it works as expected)!

Reflecting Compare-String shed some light on the behaviour (I looked at v8 of this assembly)

(Abridged)


if (Right == null)
{
   if (Left.Length == 0)
   {
     return 0;
   } 
   return 1;
}

Looking at the "len" function and is-null-or-empty confirmed that they do the same thing and should both be the same performance – though I would still use the latter as it’s clearer.


public static int Len(string Expression)
{
    if (Expression == null)
    {
       return 0;
    }
    return Expression.Length;
}

public static book IsNullOrEmpty(string value)
{
    if (value !=null)
    {
        return (value.Length== 0);
    }
    return true;
}

No comments: