Pregunta

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
¿Fue útil?

Solución

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 ;)

Otros consejos

The "If" operator used as in your example:

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

should ideally work identically to the following snippet, which does set newDateTime to Nothing:

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

In the original "If" example, VB regards 'Nothing' as the same type as myDateTime and 'Nothing' for value types in VB is just the default value of the type, so the 'Nothing' is not the same 'Nothing' when used with references types. If you change 'myDateTime' to a nullable date, then VB regards 'Nothing' as the reference type 'Nothing'. The problem is that 'Nothing' in VB is ambiguous.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top