i'm trying to build an object with below attribute
public class data
{
public string Ref{ get; set; }
public string Number { get; set; }
public string Type{ get; set; }
public string? Origin{ get; set; }
};
Thing is that : ref / Number / Type, i'll be sure to find those data in my XML file, but Origin might be null in some cases.
Below code is looped via some elt in a XML file, some times we can find origin in a collection of subelement, sometimes origin cannot be found since there is no subelement matching condition.
How can I handle this null exception while still building my object ? The goal is to have an Origin = "" if it cannot be found.
containerData.Add(new dataContainer()
{
Ref= elt.Descendants(ns "Ref")
.FirstOrDefault()
.Value,
Number = elt.Descendants(ns "Number")
.FirstOrDefault()
.Value,
Type = elt.Descendants(ns "Type")
.FirstOrDefault()
.Value,
Origin = subElement.Where(x => x.Element(ns "Name").Value == "Origin")
.Select(x => x.Element(ns "Value"))
.SingleOrDefault()
.Value,
});
trying to get Origin nullable type, but object still throwing me exception when building.
CodePudding user response:
.SingleOrDefault()
may return null
, so you may guard against that with .SingleOrDefault()?.Value
(=> Only access Value
if not null).
This leaves you with a value or null
. If you want to have an empty string in that case (if null
), you can use .SingleOrDefault()?.Value ?? ""
.
For reference: