Making the world a better place, one line of code at a time

Nothing vs Null

Posted on Wednesday, December 22, 2010, at 5:28:00 PM UTC

VB.Net’s Nothing keyword is is not the same as C#’s null.  MSDN states, “Assigning Nothing to a variable sets it to the default value for its declared type. If that type contains variable members, they are all set to their default value”.

In other words, the Nothing keyword is actually equivalent to C#’s default(T) keyword, where T is the type that the expression is used as.

This can lead to nasty surprises with nullable types in conditional operators. 
In C#, the expression (...) ? null : 1 will not compile, since “there is no implicit conversion between '<null>' and 'int'”.    Since  null is an untyped expression, the type of the conditional is inferred to be int, resulting in an error because null cannot be converted to int.

In VB.Net, by contrast, the equivalent expression, If((...), Nothing, 1), will compile, but will have unexpected results.  Here too, Nothing is an untyped expression, so the type of the conditional is inferred to be Integer.  However, unlike null, Nothing can be converted to Integer, so this is compiled as If((...), 0, 1),  which is probably not what the programmer intended.

In both languages, the solution is to use an expression which is actually typed as int?, by writing new int?(), (in C#) or New Integer?() (in VB.Net).

Categories: VB.Net, conditional, , C#, .Net, Tweet this post

comments powered by Disqus