Thursday, May 12, 2005

Freaky Nothingness

Lately I've been trying to figure out exactly how the heck Visual Basic.NET handles Nothingness.

According to the Visual Basic Language Reference, the Nothing keyword "represents the default value of any datatype". For an integer, setting it to Nothing would make its value zero. For an object, setting it to Nothing makes it an object with no reference to an instance. For a string, because strings are objects in VB.NET, setting it to Nothing would make it an object with no reference to an instance.

This is important, because I originally misunderstood the purpose and use of the Nothing keyword. I thought it was the VB.NET variable equivellant of NULL, which it decidedly is not.

Based on its name I expected setting an integer to Nothing would set it to... well, nothing instead of zero. Maybe DefaultValue would have been a better name for this keyword. Setting reference-type variables to Nothing works fine, but setting value-type variables (like integers) to Nothing doesn't buy me anything.

So how can I set VB.NET value-type variables to something like NULL?

Tony Patton's article Working with null values in .NET indicates you can set "any type of data" to DBNull, but my experiments result in Visual Studio.NET 2003 telling me it can't convert System.DBNull.Value to an integer.

The blog posting The Truth about Nullable Types and VB... provides some good information:

There is no way in the current CLR to look at an Integer variable and determine whether it has never been assigned a value - the fact that it contains zero doesn't necessarily mean that it hasn't been assigned a value.
Crap. It also says that VS.NET 2005 will be adding a generic type called Nullable(Of T) that allows you to make nullable versions of any value type. That doesn't help me much now.

I guess I'll have to revert to magic numbers to indicate that my value-type variables do not contain values.

No comments: