Given the following code:
Dim widthStr As String = Nothing
This works – width is assigned Nothing:
Dim width As Nullable(Of Double)
If widthStr Is Nothing Then
width = Nothing
Else
width = CDbl(widthStr)
End If
But this does not – width becomes 0.0 (although it seems to be logically identical code):
Dim width As Nullable(Of Double) = If(widthStr Is Nothing, Nothing, CDbl(widthStr))
Why? Is there anything I can do to make it work?
This all comes down to type analysis of expressions.
Nothingis a magical beast in VB.Net. It’s approximately the same asdefault(T)in C#.As such, when trying to determine the best type for the following:
The third argument is of type
Double. The second argument is convertible toDouble(becauseNothingcan return the default value of value types). As such, the type of the return value ofIfis determined to beDouble.Only after that piece of type analysis has concluded is any attention paid to the type of the variable to which this expression is being assigned. And
Doubleis assignable toDouble?without any warnings.There’s no clean way to make your
If()expression work how you expected. Because there’s no equivalent tonullin VB.Net. You’d need (at the least) to insert aDirectCast(or equivalent) on one side or another of the potential results of theIfto force the type analysis to seeDouble?rather thanDouble.