tags:

views:

256

answers:

5

I have the following code which seems to blow up if the column in the datarow (dr) is null. what is the correct way to parse out the value from the data row and handle null checks?

            Person person = new Person()
                                {
                                    FirstName = dr["FirstName"].ToString(),
                                    LastName = dr["LastName"].ToString(),
                                    BusinessPhoneNumber = dr["BusinessPhone"].ToString(),
+1  A: 

Pass the column, and a default value to a helper function that checks for null and returns the default if null, or the column value if not null.

Martin
+1  A: 

If the column is of type string, but is nullable, what about trying:

// FirstName must allow null
FirstName = dr["FirstName"] as string

or

// FirstName would be empty for a NULL in the database
FirstName = (dr["FirstName"] as string) ?? string.Empty
João Angelo
Strings are "nullable" by default, since they are reference types.
Fredrik Mörk
I was talking about the column and not the string type.
João Angelo
A: 

dr["FirstName"].ToString() will occasionally throw null pointer exceptions because you're trying to access ToString on a null object. Other than that, strings can be null, so really, if you know it's a string, and you don't mind that it's null, it'd be safe to do

FirstName = (String) dr["FirstName"]
David Hedlund
+1  A: 

Check for null first

FirstName = dr["FirstName"] == null ? null : dr["FirstName"].ToString()
Mark Byers
A: 

You can use the following to return a blank string if the column is null.

FirstName = string.format("{0}", dr["FirstName"])
Agent_9191