Search code examples
vb.netvisual-studio-2010datetime.net-4.5comparison-operators

Date comparison myDateTime.Equals(DateTime.MinValue) not Working in VB.Net


I use VB.Net, Visual Studio 2010, .Net version 4.5.50938 SP1Rel.

When a DateTime parameter is empty I see the value passed is #12:00:00 AM# which is basically the DateTime.MinValue. Assuming myDateTime (which is empty) is the DateTime parameter I pass,

Dim newDateTime As Nullable(Of DateTime) = If(myDateTime.Equals(DateTime.MinValue), Nothing, myDateTime)

makes newDateTime's value as "#12:00:00 AM#" instead of Nothing. I verified that the If condition is returning true. Can anyone tell me why the Nullable (Of DateTime) is not Nothing?

Also, the below code worked and does not enter the If Loop.

Dim newDateTime As Nullable(Of DateTime) = Nothing
If (Not myDateTime.Equals(DateTime.MinValue)) Then
   newDateTime = myDateTime
End If

Solution

  • With the "If" operator, both return value must be of the same type. In this case, the If returns a DateTime for both true and false. You can see this by doing the below (it won't compile).

    If(True, 123, "aaa")
    

    So you don't get a real Nothing. Instead, just return a nullable.

    Dim newDateTime As Nullable(Of DateTime) = If(myDateTime.Equals(DateTime.MinValue), New Nullable(Of DateTime), myDateTime)
    

    Or like Arman said

    Dim newDateTime As Nullable(Of DateTime) = If(myDateTime.Equals(DateTime.MinValue), CType(Nothing, DateTime?), myDateTime)
    

    Better yet, don't try to put everything on one line ;)