Comparing null DateTime values ​​in VB.net

I am a C # / asp.net developer and I need to work with VB / asp.net. I started with VB.NET, but after a few years from it I got confused in the syntax.

I have two variables

Dim originalDate as DateTime?
Dim newDate as DateTime?

Both values ​​are with zero value, originalDate is the zero date that I get from the database, and the newDate time is set in the code, I need to compare them, they can either have dates, or have dates, or one, and the other not.

I have some code as follows:

if origEndDate = origEndDate then

When both origEndDate and origEndDate are “nothing”, this statement is false (well, when I run it in the viewport, it returns as nothing)!

I don’t understand why this is so, because I had the impression that “=” compares two values, and since they are the same, should this be true?

- , ? , #, :

if (origEndDate == origEndDate) { }

.

Confused!

!

+5
5

originalDate.Equals(newDate) ?

(, NRE, null, Nullable(Of DateTime) null , .)

+4

object.equals(originalDate, newDate)

+2

GetValueOrDefault , null

Dim d1 As New Nullable(Of DateTime)
Dim d2 As New Nullable(Of DateTime)
If d1.GetValueOrDefault = d2.GetValueOrDefault Then
  {do stuff}
End If

HasValue , undefined.

If (Not d1.HasValue AndAlso Not d1.HasValue) OrElse (d1.HasValue AndAlso d2.HasValue AndAlso d1 = d2) Then
  {do stuff}
End If
+2

, Date.Equals , (, lt; > ).

, :

If Date1.GetValueOrDefault > Date2.GetValueOrDefault Then
    ...
End If

I decided to standardize all my code to use this method for reconciliation. So now my equality checks are in the same format as the example above:

If Date1.GetValueOrDefault = Date2.GetValueOrDefault Then
    ...
End If
+1
source

Use the Nullable Class methods when you need to know if two Nullables are equal

Dim d1 As New Nullable(Of DateTime)
Dim d2 As New Nullable(Of DateTime)
Dim result As String = "Not Equal"
If( Nullable.Equals(d1,d2))
    result = "Equal"
End If

You can also check more than

Dim compareResult As Integer
compareResult = Nullable.Compare(d1,d2)
If(compareResult > 0)
    result = "d1 greater than d2"
Else If (compareResult < 0)
    result = "d1 less than d2"
Else
    result = "d1 equal d2"
End If
+1
source

All Articles