views:

48

answers:

2

I was having trouble with a nullable type so I wrote the following program to demonstrate the issue I was having and am confused by the results. Here is the program:

Module Module1

Public Sub Main()
    Dim i As Integer? = Nothing
    Dim j As Integer? = GetNothing()
    Dim k As Integer? = GetNothingString()

    If i.HasValue Then
        System.Console.WriteLine(String.Format("i has a value of {0}", i))
    End If
    If j.HasValue Then
        System.Console.WriteLine(String.Format("j has a value of {0}", j))
    End If
    If k.HasValue Then
        System.Console.WriteLine(String.Format("k has a value of {0}", k))
    End If

    System.Console.ReadKey()

End Sub

Public Function GetNothingString() As String
    Return Nothing
End Function

Public Function GetNothing() As Object
    Return Nothing
End Function

End Module

The output of the program is: k has a value of 0

Why does only k have a value?

+1  A: 

It has to do with the implicit conversion of a string to an integer.

The others are set straight to Nothing or have Nothing as an Object sent to it, which doesn't have an implicit conversion. String, however, does.

Try it again with Option Strict turned on. I bet none print.

Andy_Vulhop
you were right . . . oh the joys of vb
Dustin Hodges
+1  A: 

GetNothingString returns an object of type string. With option strict turned off, the VB.Net compiler allows this, but since a String can not be directly assigned to a Nullable(Of Integer), it inserts code to convert the string to an integer. You can verify this with reflector: e.g. when decompiled to VB.Net, the code looks like this:

Dim k As Nullable(Of Integer) = Conversions.ToInteger(Module1.GetNothingString)

Since this conversion function returns an int (Integer), and not a nullable int, the default value returned can not be Nothing, but must be a valid integer, 0.

The code for the conversion from object to Integer?, OTOH, is a direct cast:

Dim j As Nullable(Of Integer) = DirectCast(Module1.GetNothing, Nullable(Of Integer))

The DirectCast would fail with an InvalidCastException at runtime if you return anything else than Nothing from that function.

jeroenh