best way to prevent Null failure with string casting best way to prevent Null failure with string casting sql sql

best way to prevent Null failure with string casting


Use the null-coalescing operator: ??

callReportCode = (reader["Call Report Code"] ?? "").ToString();

If the data in your field is DBNull.Value (rather than null), this will still work, because DBNull.Value is not null, so the ?? won't be used, and DBNull.Value.ToString() is "", which is what you'd want.


Convert.ToString(reader["Call Report Code"]);

It will return string.Empty if the value is null.

Source: http://msdn.microsoft.com/en-us/library/astxcyeh.aspx

Update: it also works with DBNull, I've just verified.

Update 2: I decided to bring a more complete test here, just to be sure:

DBNull dbNull = null;DBNull dbNullEmpty = DBNull.Value;string stringNull = null;string stringEmpty = string.Empty;var outcome1 = Convert.ToString(dbNull);//Empty stringvar outcome2 = Convert.ToString(dbNullEmpty);//Empty stringvar outcome3 = Convert.ToString(stringNull);//NULLvar outcome4 = Convert.ToString(stringEmpty);//Empty string


If your string is nullable, you need to check the value returned from the SqlDataReader against DBNull.Value:

_callReportCode = reader["Call Report Code"] as string;

If the object returned by reader["Call Report Code"] is not a string, it's DBNull.Value, so the as cast is going to set the value of _callReportCode to null as well.

If you must set the string to a non-null in case the database value is missing, add ??, like this:

_callReportCode = (reader["Call Report Code"] as string) ?? string.Empty;