Nullable type with inline if can't work together?

Given the following code:

Dim widthStr As String = Nothing 

It works - width is assigned to Nothing :

 Dim width As Nullable(Of Double) If widthStr Is Nothing Then width = Nothing Else width = CDbl(widthStr) End If 

But this is 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?

+6
source share
2 answers

It all comes down to the analysis of expression types.

Nothing is a magical beast in VB.Net. It is about the same as default(T) in C #.

Thus, when trying to determine the best type for the following:

 If(widthStr Is Nothing, Nothing, CDbl(widthStr)) 

The third argument is of type Double . The second argument is converted to Double (because Nothing can return the default value). Thus, the type of the return value of If is defined as Double .

Only after this part of the type analysis is completed does any attention be paid to the type of variable to which this expression is assigned. And is Double assigned to Double? without any warning.


There is no pure way to make your If() expression work as you expected. Because there is no null equivalent in VB.Net. Do you need to (at least) insert a DirectCast (or equivalent) with one or the other of the potential If results to make the type analysis see Double? , not Double .

+4
source

In response to Damien's answer, the clean way to do this is not to use Nothing , but New Double? instead of this:

 Dim width As Double? = If(widthStr Is Nothing, New Double?, CDbl(widthStr)) 

And now that the type of the If expression is correct, it can be reduced to:

 Dim width = If(widthStr Is Nothing, New Double?, CDbl(widthStr)) 
+10
source

All Articles