Monday, April 02, 2007

Nullable Types Not Quite There

Lately I've finally been working with Visual Studio 2005 and .NET 2.0.  Previous to this, I'd been working with 2003 and 1.1 almost entirely, and only read about (though extensively) and played with 2.0.  Since I only play with C#, I got used to all the new features it added, and wrongly assumed that Visual Basic .NET brought the same features to the table.

As I should know by now... that was a poor assumption.  I found this out today when I was trying to use Nullable types to deal with database access.  I've been working with VB most recently, so I created an empty playground project to play with the features and see how they worked.  Then I realized I had no idea how to declare a Nullable type in Visual Basic.  I'd only done it in C#.  That's no problem... a minute later I had written this sample code:

Dim n As Nullable(Of Integer)
Dim m As Nullable(Of Integer)

n = 7
m = 3

Console.WriteLine(n + m)

Hmmm... Nullable(Of Integer) isn't nearly as nice looking as int?, but VB syntax has always been more bulky to me than C#?  Hold on a second!  Why doesn't that last line compile?  Doesn't VB.NET have the same type coercion features of C# for nullable types?  That would be a definite no.

For the record, here is the identical code in C#:

int? n = 7;
int? m = 3;

Console.WriteLine( n + m );

Now then... doesn't that look nice?  And it compiles and works like you'd expect it to also.  Is that so much to ask?  So the reality is that Visual Basic only supports Nullable types because it happens to be implemented using Generics in the CLR, so Visual Basic didn't do any extra work to support them... bare bones.  But that's all you get.  Just bare bones support without any of the extra niceties that you'd expect to find.

#    8:59 PM by Nick | No Comments |