Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking a NULL value from the database and assigning to a Date variable

A stored procedure returns data about a user record including a nullable datetime column for their last login date. Which one is the better choice in dealing with the possibility for NULL values when trying to assign a .Net date variable?

    Try
        _LastLogin = CDate(DT.Rows(0)("LastLogin"))
    Catch ex As InvalidCastException
        _LastLogin = Nothing
    End Try

or

    If DT.Rows(0)("LastLogin") Is DBNull.Value Then
        _LastLogin = Nothing
    Else
        _LastLogin = CDate(DT.Rows(0)("LastLogin"))
    End If

Edit: I also forgot about the possibility of using a TryParse

    If Not Date.TryParse(DT.Rows(0)("LastLogin").ToString, _LastLogin) Then
        _LastLogin = Nothing
    End If

Which is the preferred method of handling possible NULL values from the database? Is there a better way than the three listed?

Edit #2: I have noticed that the TryParse method does not play nice when trying to assign to a Nullable type.

like image 948
TheTXI Avatar asked Dec 09 '25 12:12

TheTXI


1 Answers

The second code snippet is better. Exceptions are for exceptional cases, not cases you expect to happen. Plus, the intent is much better. It's clear that you are expecting DBNull to be a possible value and you want to handle it accordingly.

Also, you may have unintended consequences if the value is not null but not parseable (although this is likely to never happen).

like image 103
Matthew Bonig Avatar answered Dec 11 '25 20:12

Matthew Bonig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!