vb.net.net-8.0

VB (.net 8) Two simple Functions which should return same result, but don't


I have a small understanding problem. 2 simple functions that in my opinion should produce the same result, but effectively do not do so.

First (which returns expected values)

  Public Shared Function TSN(value As Object) As TimeSpan?

      If IsDBNull(value) OrElse IsNothing(value) Then
          Return Nothing
      Else
          Return DirectCast(value, TimeSpan)
      End If

  End Function

Second (Which is acting weird in my opinion)

  Public Shared Function TSN(value As Object) As TimeSpan?

      Return If(IsDBNull(value) OrElse IsNothing(value), Nothing, DirectCast(value, TimeSpan))

  End Function

Given Value is coming from an SQL query. If it's Value is DBNull or Nothing, the Functions should both return Nothing. First one does, second returns New Timespan(0,0,0). But i don't get it, because the 2nd function is actually just the short form of the first function.

I'm obviously missing something? Maybe someone here can explain it to me :)


Solution

  • The If operator has to have a specific type picked from the types of its operands.

    Nothing is special and doesn't have a type, or rather it's convertible to every possible type. The other type is TimeSpan (not TimeSpan?) so that's the type determined to be the result type of the If operator.

    And so Nothing is converted to the 0 timespan and that's the result.


    From the Specification:

    The result type of the expression is the dominant type between the types of the second and third expression. If there is no dominant type, then a compile-time error occurs.