views:

77

answers:

3

How can I improve this code? What has made this long winded is the fact that I can't use string.IsNullOrEmpty on a data row and instead I have to use a dr.IsHOUSENUMBERNull method AND the string.IsNullOrEmpty to check if it is empty. Why is this? The column in the database is sometimes empty and sometimes NULL.

I'm sure this can be written better:

     If Not dr.IsHOUSENUMBERNull Then
           If Not String.IsNullOrEmpty(dr.HOUSENUMBER) Then
                sbAddress.AppendLine(dr.HOUSENUMBER + " " + dr.ADDRESS1)
           Else
                sbAddress.AppendLine(dr.ADDRESS1)
           End If   
     Else
           sbAddress.AppendLine(dr.ADDRESS1)      
     End If
+3  A: 

You could do this, a bit shorter:

 If dr.IsHOUSENUMBERNull OrElse String.IsNullOrEmpty(dr.HOUSENUMBER) Then
       sbAddress.AppendLine(dr.ADDRESS1) 
 Else     
       sbAddress.AppendLine(dr.HOUSENUMBER + " " + dr.ADDRESS1)
 End If

Or if you want it more terse, though less readable in this case I think, use If():

sb.Address.AppendLine(If(r.IsHOUSENUMBERNull OrElse String.IsNullOrEmpty(dr.HOUSENUMBER), dr.ADDRESS1, dr.HOUSENUMBER + " " + dr.ADDRESS1))
Nick Craver
Both your samples will throw an excepton if dr.HOUSENUMBER contains DBNull. You should use **OrElse** (short circuited) instead of **Or**
Alfred Myers
@Alfred - Thanks for reminding me why I don't do VB anymore :) fixed!
Nick Craver
Thanks guys this is wonderful.
Jon
A: 

I think only this much code is sufficient:

If Not String.IsNullOrEmpty(dr.HOUSENUMBER) Then 
   sbAddress.AppendLine(dr.HOUSENUMBER + " " + dr.ADDRESS1) 
Else 
   sbAddress.AppendLine(dr.ADDRESS1) 
End If 
Aseem Gautam
Referencing dr.HOUSENUMBER when the field is null will throw a strong typing exception. Datasets attempt to cast the value out of the row when you access the property. This is one of the most annoying things about them.
DoctaJonez
If the original column datatype is not string then it will throw an exception. If column 'HOUSENUMBER' is of type string, String.IsNullOrEmpty should work fine.
Aseem Gautam
A: 

There is a difference between the database's NULL and .NET's null (VB's Nothing when applied to reference types).

string.IsNullOrEmpty looks for .NET's null - not the database's NULL. So there is no need to check for null - only NULL/DBNull

If you store a database's NULL or .NET's null into a DataTable, you'll get back a DBNull.

AppendLine(object) call's object.ToString()

DBNull.Value.ToString() returns ""

Given all this information, your code could be simplified to:

sbAddress.Append(dr.HOUSENUMBER)
If Not dr.IsHOUSENUMBERNull AndAlso dr.HOUSENUMBER.Length <> 0 Then
    sbAddress.Append(" ")
End If
sbAddress.AppendLine(dr.ADDRESS1)  
Alfred Myers