Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Object Reference

Using Nunit to test C# code with the following code block:

foreach (XmlNode node in nodeList)
{
    thisReport.Id = node.Attributes.GetNamedItem("id").Value;
    thisReport.Name = node.Attributes.GetNamedItem("name").Value;
    thisReport.Desc = node.Attributes.GetNamedItem("desc").Value;
    if (node.SelectNodes("subreport").Count > 0)
    {
        thisReport.HasSubReport = true;
        subReportNodeList = node.SelectNodes("subreport");
        foreach(XmlNode subNode in subReportNodeList)
        {
            mySubReport.ParentID = node.Attributes.GetNamedItem("id").Value;
            mySubReport.Priority = subNode.Attributes.GetNamedItem("priority").Value;
            mySubReport.SubReportId = subNode.Attributes.GetNamedItem("id").Value;
            mySubReport.SubReportName = subNode.Attributes.GetNamedItem("name").Value;
            string sTime = subNode.Attributes.GetNamedItem("time").Value;
            mySubReport.Time = Convert.ToInt16(sTime);
            thisReport.SubReportsList.Add(mySubReport);
        }
    }
    else
    {
        thisReport.HasSubReport = false;
    }
    reports.Add(thisReport);
}

The code fails with a null object reference on the line:

            thisReport.SubreportsList.Add(mySubReport)

But looking at the locals, thisReport exists and has the values assigned at the top of the block, and mySubReport exists and has the values assigned just above the line where it's added to thisReport. All the values in mySubReport are valid and SubReportsList in thisReport is a generic list of type SubReport.

So, where's the null? It seems so simple, it must be something really obvious that I can't see.

like image 673
EoRaptor013 Avatar asked May 30 '26 10:05

EoRaptor013


2 Answers

You've not instantiated SubReportsList before calling Add. Do the following before adding mySubReport:

thisReport.SubReportsList = new List<SubReport>();
thisReport.SubReportsList.Add(mySubReport);

You could also change your SubReportsList property to make your life easier:

public class Report
{
    public IList<SubReport> SubReportsList
    {
        get
        {
            if (_subReportsList == null)
            {
                _subReportsList = new List<SubReport>();
            }
            return _subReportsList;
        }
    }
    private IList<SubReport> _subReportsList;
}

Doing this would instantiate your List if it's called while it's null.

like image 134
djdd87 Avatar answered Jun 01 '26 00:06

djdd87


You should probably first do:

thisReport.SubReportsList = new List<SubReport>();
like image 23
Dan Dumitru Avatar answered May 31 '26 23:05

Dan Dumitru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!