HumbleBeginnings
HumbleBeginnings

Reputation: 1019

VB.NET 2015 Nullable Integer Not Working with If() operator?

Why is this result 0 (zero) and NOT Nothing?

Dim foobar As Integer? = If(False, 1, Nothing)

From Microsoft Documentation:

If a variable is of a value type, the behavior of Nothing depends on whether the variable is of a nullable data type. To represent a nullable value type, add a ? modifier to the type name. Assigning Nothing to a nullable variable sets the value to null. For more information and examples, see Nullable Value Types.

Further research yields even more interesting results:

Dim foo As Integer? = If(False, 1, Nothing)             '0
Dim bar As String = If(False, 1, Nothing)               '"0"
Dim bar2 As String = If(False, "1", Nothing)            'Nothing
Dim bar3 As Integer? = If(False, "1", Nothing)          'Nothing
Dim bar4 As Integer? = If(False, CStr(1), Nothing)      '0

Does the following suggest that the result type is predicated on the type second value?

Dim bar3 As Integer? = If(False, "1", Nothing)          'Nothing

EDITED with additional finding and desired result, but why should BOTH arguments need to be evaluated and not just the short-circuited version of If()?

Dim foo As Integer? = IIf(False, 1, Nothing)             'Nothing

Upvotes: 3

Views: 494

Answers (2)

EvilDr
EvilDr

Reputation: 9632

In addition to dbasnett's answer, you can do:

Dim foo As Integer? = If(False, 1, CType(Nothing, Integer?))

Upvotes: 0

dbasnett
dbasnett

Reputation: 11773

A fix for If operator,

Dim foo As Integer? = If(False, 1, New Nullable(Of Integer))

and one other

    Dim foo As Integer?
    If True Then
        foo = 1
    End If

Upvotes: 4

Related Questions