On assigning null to value-types in VB.NET

Posted on April 16, 2008



Consider the following generic function written in VB.NET:

Public Function Foo(Of T)() As String
Dim x As T = Nothing ‘ Line – 1
If x Is Nothing Then
Return “x is null”
Return “x is not null”
End If
End Function

What message do you expect to be shown by the following bit of code?

Dim result As String

result = Foo(Of Integer)()

Would the “Foo” method even compile? It doesn’t make sense to assign a Nothing (VB.NET equivalent of C#’s null) to a value-type, right?


Well, the code compiles just fine. When synthesizing a Foo method for Integers, the VB.NET compiler silently munges line-1 to assign a zero to our local variable “x”.

C# on the other hand, has the “default” keyword which you can use to get the default value associated with a generic type. This default value is “null” for reference types, and the value generated by bitwise zeroing of the whole thing in case of value types. Assigning a “null” to a value-type in C# leads to a compilation error.

I find the VB.NET semantics in this regard slightly broken. “0” is not the same as “Nothing”, but if you assign a “Nothing” to something, a check to see if it still contains “Nothing” should succeed.

Anyway, the message you’d see is “x is not null” for the previous code listing. If on the other hand, you had code like the following:

result = Foo(Of String)()

…the message you’d see is “x is null”.

About these ads
Posted in: .NET, Tech/Hacks