Ebikeneser
Ebikeneser

Reputation: 2364

Object reference not set to an instance of an object

I have the following code -

private static void convert()
    {
        string csv = File.ReadAllText("test.csv");
        XDocument doc = ConvertCsvToXML(csv, new[] { "," });
        doc.Save("update.xml");

        XmlTextReader reader = new XmlTextReader("update.xml");
        XmlDocument testDoc = new XmlDocument();
        testDoc.Load(@"update.xml");

        XDocument turnip = XDocument.Load("update.xml");
        webservice.function[] test = new webservice.function[1];
        webservice.function CallWebService = new webservice.function();

        foreach(XElement el in turnip.Descendants("row"))
        {
                            test[0].com = System.Convert.ToInt32(el.Descendants("var").Where(x => (string)x.Attribute("name") == "com").SingleOrDefault().Attribute("value").Value);
            test[0].Centre = el.Descendants("var").Where(x => (string)x.Attribute("name") == "Centre").SingleOrDefault().Attribute("value").Value;
            test[0].CCentre = el.Descendants("var").Where(x => (string)x.Attribute("name") == "CCentre").SingleOrDefault().Attribute("value").Value;

            MessageBox.Show(test[0].person, "person");
            MessageBox.Show(System.Convert.ToString(test[0].actually), "Actually");
            MessageBox.Show(System.Convert.ToString(test[0].com), "Com");

            CallWebService.updateFeedStatus(test);
        }

It is coming up with the error of - NullReferenceException was unhandled, saying that the object reference not set to an instance of an object. The error occurs on the first line test[0].account.

How can I get past this?

Upvotes: 2

Views: 3397

Answers (3)

jjrdk
jjrdk

Reputation: 1892

I'm guessing your xml has a namespace that you need to include in your xname for the desired elements, but as the other comments mention, there is little that can be done without full disclosure.

Upvotes: 1

Justin
Justin

Reputation: 6711

Initializing an array does not initialize the objects in the array. Try adding the second line below (assuming you want to use the default constructor):

webservice.singleSummary[] test = new webservice.singleSummary[1];
test[0] = new webservice.singleSummary();

Upvotes: 6

Chris B. Behrens
Chris B. Behrens

Reputation: 6295

  1. Put a debugger on the process.
  2. Identify which line of code is generating the error. (Assuming Visual Studio)
  3. Test the object references on that line one by one until you determine which one has the null reference.
  4. Put in a null check before the line to fix the problem.

Upvotes: 2

Related Questions