Existe alguma diferença entre usar .getValueDefault (0) e se (variável, 0) com tipos anuláveis?
Pergunta
Existe alguma diferença entre os 2 métodos abaixo para calcular C ... Especificamente os problemas de boxe/unboxing?
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)
Solução
Segundo o Reflector, o IL do seu snippet de código se decima:
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
Editar] e depois olhando para as funções refletidas GetValueOrDefault()
e GetValueOrDefault(T defaultValue)
dá o seguinte (respectivamente):
Public Function GetValueOrDefault() As T
Return Me.value
End Function
e
Public Function GetValueOrDefault(ByVal defaultValue As T) As T
If Not Me.HasValue Then
Return defaultValue
End If
Return Me.value
End Function
Indicando qualquer uma das formas é efetivamente exatamente a mesma coisa
Outras dicas
A instrução C = if (a, 0) + if (b, 0) é compilada a isto:
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
O segundo trecho é compilado exatamente como está. É o vencedor claro aqui.
a.GetValueOrDefault(0)
é uma versão um pouco mais eficiente de If(a, 0)
a.GetValueOrDefault()
é uma versão um pouco mais eficiente de a.GetValueOrDefault(0)
Obviamente, isso é verdade apenas para tipos numéricos.