Why I can't set Nothing to Nullable(Of Double) through conditional ternary operator but I can directly?
Dim d As Double? = Nothing
d = If(True, 0, Nothing) ' result: d = 0
d = Nothing ' result: d = Nothing
d = If(False, 0, Nothing) ' result: d = 0 Why?
Edit: These work (based on below accepted answer):
d = If(False, 0, New Integer?)
d = If(False, CType(0, Double?), Nothing)
d = If(False, 0, CType(Nothing, Double?))
Nothing
converts to a lot of types, not just T?
. It can happily convert to Double
:
Function X() As Double
Return Nothing ' result: 0.0
End Function
or to Integer
. It's that sense of Nothing
that you're using in If(X, 0, Nothing)
, because If
needs the second and third arguments to match in type: it treats it as type Integer
, because that's the type of 0
.
Explicitly specifying one of the types as nullable (either Integer?
or Double?
would work) lets the compiler figure out what you want:
d = If(False, CType(0, Double?), Nothing)
, or d = If(False, 0, CType(Nothing, Double?))