views:

193

answers:

2

I am building an xml file. Parts of the file are static. Some of the file is dynamic. My code has an error of “Null object reference”.

Any tips would be awesome.

private XElement BuildDataElement()
{
    // this is going to be more complicated
    return new XElement("data");
}

public void TestXML(string fname)
{
    // build the data element
    XElement allData = BuildDataElement();

    // Build the header
    XDocument doc = new XDocument(
        new XElement("map",
            new XAttribute("showLabels", "1"),
            new XAttribute("includeNameInLabels", "1"),
            new XElement("colorRange",
                new XElement("color",
                new XAttribute("minValue", "1")
                )
            ),
            allData,
            new XElement("application",
                new XElement("apply",
                    new XAttribute("toObject", "TOOLTIP"),
                    new XAttribute("styles", "TTipFont,MyDataPlotStyle")
                )
            )
         )
     );

    if (File.Exists(fname))
        File.Delete(fname);
    doc.Save(fname);
         }
A: 

The only way in the snippet provided I can see getting an error would be 2 two places.

BuildDataElement();

Could be generating the error, rather than the Xml document.

Next if BuildDataElement(); returns that might be the problem, since I am guessing the XDocument is doing a .ToString() or some action on allData

David Basarab
+4  A: 

Any tips would be awesome.

You got it. Here are my tips:

  • Obtain a debugger.
  • Set the debugger to break at all exceptions.
  • Run your code in the debugger until the null reference exception happens.
  • Figure out which value was null that you did not expect to be null.
  • Either insert a check for null that handles the situation where the value is null correctly, or change the logic so that it becomes impossible for that value to be null.
  • Thoroughly code-review and test the fix.
  • Write a regression test for your test suites that verifies that this bug doesn't come back.
Eric Lippert
Agreed, figure out the line the error is on with a debugger first instead of posting the whole method.
jarrett