Is there any difference between using .GetValueOrDefault(0) and If(variable, 0) with nullable types?
Is there any difference between the 2 methods bel开发者_如何学运维ow 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)
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
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.
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.
精彩评论