Some Creativity

Weblog of Siddharth Uppal

On assigning null to value-types in VB.NET

leave a comment »

Problem:

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"
        Else
            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)()
        MessageBox.Show(result)

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?

Solution:

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)()
        MessageBox.Show(result)

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

Written by Sid

April 16, 2008 at 5:15 pm

Posted in .NET, Tech/Hacks

Tagged with , , ,

Leave a Reply