Question

Can this code be tightened up?

Is a DataTable.Rows.Count check needed if a TryParse needs to be done anyway?

If dtDataTable.Rows.Count > 0 Then
    Try
        Boolean.TryParse(dtDataTable.Rows.Item(0).Item("IsBoolValue").ToString(), m_bBoolean)
    Catch ex As Exception
        ' we got a NULL
        m_bBoolean = False
    End Try
Else
    m_bBoolean = False
End If

Thanks.

Was it helpful?

Solution

Yes because if there are no rows, the expression

dtDataTable.Rows.Item(0).Item("IsBoolValue").ToString() 

produces an NullReferenceException before being analyzed by the TryParse and you don't want to drive your code using an exception handler like that. The cost to use a simple IF before the test is really minimal compared to the cost to handle an exception.

Also, I think that it is better to introduce a test on DBNull.Value to avoid any possible exception

m_bBoolean = False
If dtDataTable.Rows.Count > 0 Then
    if(dtDataTable.Rows.Item(0).Item("IsBoolValue") <> DBNull.Value) Then
        Boolean.TryParse(dtDataTable.Rows.Item(0).Item("IsBoolValue").ToString(), m_bBoolean)
    End if
End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top