Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 754
burlmd Avatar asked Nov 19 '25 00:11

burlmd


1 Answers

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

like image 128
jeffora Avatar answered Nov 20 '25 15:11

jeffora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!