views:

218

answers:

3

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)
A: 

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

jeffora
A: 

a.GetValueOrDefault(0) is a slightly more efficient version of If(a, 0)

a.GetValueOrDefault() is a slightly more efficient version of a.GetValueOrDefault(0)

Of course, this is only true for numeric types.

Gabe
+1  A: 

The c = If(a, 0) + If(b, 0) statement gets compiled to this:

  Dim tmpa As Integer
  If a.HasValue Then
    tmpa = a.GetValueOrDefault()
  Else
    tmpa = 0
  End If
  Dim tmpb As Integer
  If b.HasValue Then
    tmpb = b.GetValueOrDefault()
  Else
    tmpb = 0
  End If
  c = tmpa + tmpb

The second snippet gets compiled exactly as-is. It is the clear winner here.

Hans Passant