Reputation: 611
I am reading an rss feed which has "credit" node in my item in most of the cases. While in some case it is not there..how do I avoid getting object not set exception? I am reading it this way using linq in c#
Credit = (string)item.Element(media + "credit").Value == null ? string.Empty : (string)item.Element(media + "credit").Value,
Upvotes: 0
Views: 48
Reputation: 236278
You should check if element is not null before retrieving elements value:
var creditElement = item.Element(media + "credit");
Credit = (creditElement == null) ? string.Empty : (string)creditElement.Value;
But Linq is smart enough - it can explicitly cast element value to string and treat missing element as null. So you can just convert element to string, and with null coalescing operator assign default value:
Credit = (string)item.Element(media + "credit") ?? String.Empty;
Upvotes: 1