How to Keep from Receiving a NullReferenceException when Accessing the Result of a Web Service?
I am getting a response in form of a SOAP message from a web service. I don't know on beforehand what nodes are available (some but not all). Lets say I get data about a customer
Name
Cityand in the code I can write
string name = "";
string city = "";
name = customer.name;
city = customer.city;
If the city returns an empty string I can handle that with writing
ci开发者_如何学运维ty = (string)customer.city;
instead. But sometimes the response doesn't include a city node and then I get the NullReferenceException was unhandled error, how can I fix this?
Are you actually asking for this:
city = customer != null ? customer.city : "";
?
Incidentally, casting a string
to a string
as you have here: (string)""
(the equiavlent of (string)customer.City
when customer.City == ""
) is not necessary. (Unless of course customer.City
is somehow actually not a string
.)
You can also use the ?? operator. This is assuming the customer object will always not be null.
string city = customer.city ?? ""
精彩评论