DBNull – Using ToString() vs. Casting

You can use ToString on any indexed value in a DataRow, and it will return null if the field is DBNull:

string myNullableField = row["MyField"].ToString();

However, if you try to cast that same field as a string, you’ll get an exception:

string myNullableField = (string)row["MyField"]; //InvalidCastException!

But, the good thing about the InvalidCastException being thrown, is this gives us a nice little trick. We can use casting as a fail-safe. If we have a non-nullable field, and we get DBNull for ANY reason, we WANT the CLR to throw an exception (it makes it super-easy to debug):

string myNeverNullField = (string)row["MyField"];  
 //"MyField" is non-nullable. if we ever get NULL, 
 // something went wrong; let's raise a red flag 

Your Thoughts?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s