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