How to set Nothing to a Datetime variable?

Asked

Viewed 181 times

2

I have a function that receives a string and is converted to date time, I did a check for when come string empty, return Nothing. But when I leave the function is returning me the date in this format #12:00:00 AM#, what I want is for you to just come Nothing or something like.

Here is my variable that gets the return:

Dim data as DateTime? = RetornaDataFormatada(strValor)

And here my reduced function:

Public Function RetornaDataFormatada(ByVal strValor As String) As DateTime

        If strValor = "" Then

            Return Nothing

        End If

        Return Nothing

End Function

1 answer

2


To DateTime cannot, this is a type per value that does not accept null values. However it is possible to return Nothing for a guy DateTime?. It seems to me that there would be no problem for you since you will use in a variable of this type.

Note that the interrogation makes all the difference, with and without are different types, with different semantics.

This way just change the type of returns, like this:

Public Function RetornaDataFormatada(ByVal strValor As String) As DateTime?
    If strValor = "" Then
        Return Nothing
    End If
    Return Nothing
End Function

I put in the Github for future reference.

Evidently this function does nothing useful but return Noting in all situations. This is not important for the question problem but gets the hint if you didn’t notice.

  • Dude, I thought about it, I even did, the problem is that it uses in several places ai of explicit conversion error! you think this is the best way, and I change the call locations of that function?

  • It’s the only way to what you want. The error you are getting is obviously normal, you would have to make adaptations on all these links to treat appropriately. If there are places waiting for one DateTime, cannot receive a DateTime? with impunity, because in the second you can have an invalid value in the first. Then you can only make the conversion explicitly. Which I don’t know if you should. At least should not without conditionally safeguarding.

  • Okay, I’ll follow your lead, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.