rasputino
rasputino

Reputation: 799

One line If in VB.Net does not return nullable integer

I detected a strange behavior in the on line If statement in VB.Net

If you check this code: jdoodle.com/a/X20

Imports System

Public Class Test
    Public Shared Sub Main()
        Dim x as Integer?

        Dim ob1 As Objeto = New Objeto()
        ob1.Valor = 1
        Dim obnull As Objeto = Nothing

        x = If(obnull Is Nothing, Nothing, obnull.Valor)

        System.Console.WriteLine(x)

        If Not obnull Is Nothing Then
            x = obnull.Valor
        Else
           x = Nothing
        End If

        System.Console.WriteLine(x)


    End Sub
End Class

Public Class Objeto
    Public Valor As Integer
End Class

It returns 0 in the x = If(obnull Is Nothing, Nothing, obnull.Valor) statement instead of a null value.

Why?

Upvotes: 1

Views: 1186

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

There's nothing strange about that behaviour. The If operator is effectively generic, i.e. the return type is inferred from the common type of the second and third arguments. The third argument is type Integer and Nothing can be interpreted as type Integer too so it is. Nothing as an Integer is zero so that's what you get. If you want If to return an Integer? then at least one of the arguments needs to be that type and the other must be able to be interpreted as that type.

Dim obj As Object
Dim int = 100

Dim result1 = If(obj Is Nothing, Nothing, int)
Dim result2 = If(obj Is Nothing, DirectCast(Nothing, Integer?), int)
Dim result3 = If(obj Is Nothing, Nothing, New Integer?(int))

In that code, result1 is type Integer and will be equal to zero while both result2 and result3 will be type Integer? and will both have no value.

Upvotes: 3

Related Questions