Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to prevent Null failure with string casting

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

I am attempting to handle the possibility for the object I am calling ToString on to be NULL. I am going to be using the above statement with several variables and I dont want to make an individual try/catch for each one... what is the best way to do null checking for strings.

Other datatypes ive been doing this:

int.TryParse(reader["Account Number"].ToString(), out _accountNumber);

In this code "reader" refers to a SqlDataReader but thats not really important for this question.

like image 573
jth41 Avatar asked Apr 05 '13 13:04

jth41


People also ask

How do you avoid null?

One way of avoiding returning null is using the Null Object pattern. Basically you return a special case object that implements the expected interface. Instead of returning null you can implement some kind of default behavior for the object. Returning a null object can be considered as returning a neutral value.

What happens if you use null value in string interpolation?

If the interpolation expression evaluates to null , an empty string ("", or String. Empty) is used. If the interpolation expression doesn't evaluate to null , typically the ToString method of the result type is called.

Can you cast null to string?

You can cast null to any source type without preparing any exception. The println method does not throw the null pointer because it first checks whether the object is null or not. If null before it simply prints the string "null". Otherwise, it will call the toString purpose of that object.


1 Answers

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.

like image 189
Bobson Avatar answered Oct 16 '22 08:10

Bobson