Nick
Nick

Reputation: 143

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
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

city = (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?

Upvotes: 0

Views: 159

Answers (2)

user342706
user342706

Reputation:

You can also use the ?? operator. This is assuming the customer object will always not be null.

string city = customer.city ?? ""

Upvotes: 0

Kirk Woll
Kirk Woll

Reputation: 77606

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.)

Upvotes: 1

Related Questions