Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# – Building an object that might contains null ref

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

.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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading