Search code examples
vb.netnullableboxingunboxing

Is there any difference between using .GetValueOrDefault(0) and If(variable, 0) with nullable types?


Is there any difference between the 2 methods below for calculating c ... specifically boxing/unboxing issues?

Dim a As Integer? = 10
Dim b As Integer? = Nothing
Dim c As Integer

' Method 1
c = If(a, 0) + If(b, 0)

' Method 2
c = a.GetValueOrDefault(0) + b.GetValueOrDefault(0)

Solution

  • According to Reflector, the IL from your code snippet decompiles into:

    Public Shared Sub Main()
        Dim a As Integer? = 10
        Dim b As Integer? = Nothing
        Dim c As Integer = (IIf(a.HasValue, a.GetValueOrDefault, 0) + IIf(b.HasValue, b.GetValueOrDefault, 0))
        c = (a.GetValueOrDefault(0) + b.GetValueOrDefault(0))
    End Sub
    

    [EDIT] And then looking at the Reflected functions GetValueOrDefault() and GetValueOrDefault(T defaultValue) gives the following (respectively):

    Public Function GetValueOrDefault() As T
        Return Me.value
    End Function
    

    and

    Public Function GetValueOrDefault(ByVal defaultValue As T) As T
        If Not Me.HasValue Then
            Return defaultValue
        End If
        Return Me.value
    End Function
    

    Indicating either form does effectively exactly the same thing