none
Bug in inline IF RRS feed

  • Question

  • I have the following code:

            Dim test As Date? = Nothing
            Dim result As Date? = Nothing
            result = If(IsNothing(test), Nothing, CDate(test))

    The expected output for result is Nothing but the result variable ends up having the System Min Date #01/01/0001 12:00:00 AM#

    The only workaround that I've found so far is to convert the in-line IF statement to a regular block IF in which case it works correctly.

    Please advise or point out if there is a known issue with in-line IF statements in VB.NET.  I am using Visual Studio 2017 v4.7.02556.  Thanks!!


    • Edited by compilethis Thursday, March 29, 2018 2:24 PM
    Thursday, March 29, 2018 2:16 PM

Answers

  • The default return value of the If() method is going to be Date because of the CDate() and Nothing objects - the only inferable return type is Date.  Since you return Nothing for a Date type you get the default instance of Date.  Instead you need to make the If() return a Nullable(Of Date):

    Dim test As Date? = Nothing
    Dim result As Date? = Nothing
    result = If(IsNothing(test), New Date?, test)
    
    You have to ensure that the results of the If() function include the desired return types.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    • Marked as answer by compilethis Thursday, March 29, 2018 2:46 PM
    Thursday, March 29, 2018 2:26 PM
    Moderator

All replies

  • The default return value of the If() method is going to be Date because of the CDate() and Nothing objects - the only inferable return type is Date.  Since you return Nothing for a Date type you get the default instance of Date.  Instead you need to make the If() return a Nullable(Of Date):

    Dim test As Date? = Nothing
    Dim result As Date? = Nothing
    result = If(IsNothing(test), New Date?, test)
    
    You have to ensure that the results of the If() function include the desired return types.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    • Marked as answer by compilethis Thursday, March 29, 2018 2:46 PM
    Thursday, March 29, 2018 2:26 PM
    Moderator
  • Good answer.  Thank you!
    Thursday, March 29, 2018 2:46 PM