Sunday 8 December 2013

Nothing is not null

I have to switch between writing legacy vb.net and c# on a daily basis and generally don't find this to be much of a problem, but a came across an interesting difference when trying to find the equivalent of c#'s default keyword. The default keyword returns the default value for a type T: default(T), zero for numeric types, null for nullables etc. It turns out that Nothing can be used in vb.net in this way. I always assumed null and Nothing where equivalent between vb.net and c#; I was wrong.

null == 0 // False
Nothing = 0 ' True

false == null // False
False = Nothing ' True
Taken from the official documentation: Nothing represents the default value of any data type. For reference types, the default value is the null reference. For value types, the default value depends on whether the value type is nullable.

There doesn't appear to be an equivalent of pure null in vb.net, you would have to check if it was a reference or value type explicitly. I don't like the implicitness of Nothing, but it fits with vb.net's general implicit conversions (which I also don't like).

False = 0 ' True
"1" = 1 ' True
' etc. etc.