I'm populating an anonymous object from an XML file. Up until now,
commentary.Elements("Commentator")
has always had a value so i've never had to check for null. I've had to remove that though, and now it's failing when it tries to read that line.
I'm looking at the code and I don't know what to change though, because its being selected into a property of an anonymous object.
var genericOfflineFactsheet = new
{
Commentary = (from commentary in doc.Elements("Commentary")
select new
{
CommentaryPage = (string)commentary.Attribute("page"),
BusinessName = (string)commentary.Attribute("businessName"),
Commentator = (from commentator in commentary.Elements("Commentator")
select new CommentatorPanel // ASP.NET UserControl
{
CommentatorName = (string)commentator.Attribute("name"),
CommentatorTitle = (string)commentator.Attribute("title"),
CommentatorCompany = (string)commentator.Attribute("company")
}).FirstOrDefault()
}).FirstOrDefault()
The thing is, I can't completely remove the line because sometimes commentary.Elements("Commentator")
does have a value. I'm sure this issue has been dealt with before, but I can't see what to do. Any ideas?
I use the ? operator this way to prevent a XMLElement to be generated:
Example:
In this case, the XElement will not be generated if the object involved in its creation is null.
This is a case where I might consider the ?? (coalesce) operator.
In this case you could get away with coalescing to an empty Enumerable.
Untested...
how about something like:
Just add a null check. (code below should be a good tester. Has one with and one without Commentator)