Reputation: 7319
dim val1 As Integer? = If(5 > 2, Nothing, 43)
' val1 = 0
dim val1 As Integer? = If(5 > 2, Nothing, Nothing)
' val1 = Nothing
What gives? Is this a bug, or am I overlooking something?
Upvotes: 2
Views: 1210
Reputation: 26853
The problem is that Nothing
in VB.NET works differently than, for example, null
in C#. When Nothing
is used in the context of a value type (such as Integer
) it represents the default value of that type. In this case, that's 0.
In your first example, both branches of the ternary operator are valid Integer
values. The true branch represents 0 and the false branch represents 43.
In the second example, neither branch of the ternary operator is a valid Integer
value, thus forcing the VB.NET compiler to assume that the overall operator returns Object
, not Integer
.
To make the first example work the way you intend, you need to make it clear to the compiler that the ternary operator should resolve to an Integer?
, not an Integer
or an Object
. You can do so like this:
dim val1 As Integer? = If(5 > 2, Nothing, New Integer?(43))
By explicitly making the false branch of the operator an Integer?
, the Nothing
in the true branch will represent the null value, instead of the default Integer
value.
Upvotes: 13