开发者

How to Keep from Receiving a NullReferenceException when Accessing the Result of a Web Service?

开发者 https://www.devze.com 2023-02-08 18:03 出处:网络
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).

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

City

and 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 ?? ""

0

精彩评论

暂无评论...
验证码 换一张
取 消