"Value cannot be null" when creating an XElement from attributes where one or more of the values ​​are null

I am trying to execute the following code:

XElement element = new XElement("ENTS", from i in notificationsTracking
select new XElement("ENT", 
new object[] {
    new XAttribute("ENTID", i.TrackingID),
    new XAttribute("PID", i.Response?.NotificationProvider),
    new XAttribute("UID", i.Response?.NotificationUniqueId)
}));

      

This works great when the response is not null and there are values ​​in the "NotificationProvider" or "NotificationUniqueId" fields. But in case any of these three values ​​are null, I get an error: "The value cannot be null."

I know there is one solution where I can explicitly compare the object / properties to Null / Empty and can convert them accordingly and that will work.

But is there an optimized or more efficient way to solve this problem?

Thanks and regards,

Nirman

+3


source to share


1 answer


You can do it with just one null check (and you don't need the [] object):

XElement element = new XElement("ENTS", from i in notificationsTracking
select new XElement("ENT", 
    new XAttribute("ENTID", i.TrackingID),
    i.Response != null ? new [] {
        new XAttribute("PID", i.Response.NotificationProvider),
        new XAttribute("UID", i.Response.NotificationUniqueId),
        // more i.Response props ...
    } : null
));

      



Or, if only two just repeat the check:

XElement element = new XElement("ENTS", from i in notificationsTracking
select new XElement("ENT", 
    new XAttribute("ENTID", i.TrackingID),
    i.Response != null ? new XAttribute("PID", i.Response.NotificationProvider) : null,
    i.Response != null ? new XAttribute("UID", i.Response.NotificationUniqueId) : null
));

      

+2


source







All Articles