Reputation: 143
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
Reputation:
You can also use the ?? operator. This is assuming the customer object will always not be null.
string city = customer.city ?? ""
Upvotes: 0
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