I am having a problem fixing this error: Object reference not set to an instance of an object,

namespace FaultTrees
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            this.LoadXML();
        }
        private void LoadXML()
        {
                List<FaultTree> faultTrees = new List<FaultTree>();
                XDocument FaultTreeXML = XDocument.Load("testtrees.xml");

                faultTrees = this.GetFaultTrees(FaultTreeXML.Element("HiP-HOPS_Results"));

            this.TreeView.ItemsSource = faultTrees;
         }

        private List<FaultTree> GetFaultTrees(XElement element)
        {
            return (from faultTree in element.Elements("FaultTrees")
                    select [B]new FaultTree()
                    {
                        Name = faultTree.Attribute("Events").Value,
                        SubCategories = this.GetFaultTrees(faultTree)
                    }).ToList();[/B]
        }
    }
}

the bold section is where it is tripping up, any help would be appreciated

Recommended Answers

All 18 Replies

Which value is returning null, you can hover your mouse over variables to see their values when exceptions are thrown. Object reference exception means there is a null value somewhere in your source. Find out where it is and I'll be able to help further.

I would give an explicit path to the .xml file.
You're trusting the program to use "current directory" to load the file, but that could be failing you.

I would first modify this:

XDocument FaultTreeXML = XDocument.Load("c:/science/somwhwere/testtrees.xml");

I think that it is the Name in the

Name = faultTree.Attribute("Events").Value

line

and to thines01 I am using Silverlight so it didn't like me explicitly stating a path

Where is the name variable declared, and how is it declared?

String Name = String.Empty;

// or

string Name = "";

It could also be that faultTree isn't refereneced. Yes, now that I'm looking at the code, find a way to assign the value you return before selection because it looks as if it's not being initialized after the return. So create another variable to store the result from the return in, instead of returning try assigning the value.

Where is the name variable declared, and how is it declared?

String Name = String.Empty;

// or

string Name = "";

It could also be that faultTree isn't refereneced. Yes, now that I'm looking at the code, find a way to assign the value you return before selection because it looks as if it's not being initialized after the return. So create another variable to store the result from the return in, instead of returning try assigning the value.

sorry yea the Name is a method called in a separate class:

namespace FaultTrees
{
    public class FaultTree
    {
       public string Name
            {
                get;
                set;
            }
       public List<FaultTree> SubCategories
            {
                get;
                set;
            }
        }
    }

And it says that "Name "" "

But where are you declaring Name? You can't just have

Name = faultTree.Attribute("Events").Value

without saying what Name is, particularly if Name is in another class. You would need to declare it in the usual way before using it.

But where are you declaring Name? You can't just have

Name = faultTree.Attribute("Events").Value

without saying what Name is, particularly if Name is in another class. You would need to declare it in the usual way before using it.

As stated in my previous post Name is a method called in a different class

without saying what Name is, particularly if Name is in another class. You would need to declare it in the usual way before using it.

If it's not giving a error saying that "the current variable doesn't exist in this context", then he has declared the variable. If he's getting the object reference error, then it's recognized by the compiler at runtime.

Try using a try and catch block to see what the error is being caused by. I'm still thinking that your faultTree value isn't being referenced correctly, I get it all the time with loops and other tricky blocks. Happy new year and let me know what it tells you.

try
{
// your code
}

catch (Exception w)
{
MessageBox.Show(w.Message);
}

If it's not giving a error saying that "the current variable doesn't exist in this context", then he has declared the variable. If he's getting the object reference error, then it's recognized by the compiler at runtime.

Try using a try and catch block to see what the error is being caused by. I'm still thinking that your faultTree value isn't being referenced correctly, I get it all the time with loops and other tricky blocks. Happy new year and let me know what it tells you.

try
{
// your code
}

catch (Exception w)
{
MessageBox.Show(w.Message);
}

Having tried the try catch it now states that

private List<FaultTree> [B]GetFaultTrees[/B](XElement element)

Error 1 'FaultTrees.MainPage.GetFaultTrees(System.Xml.Linq.XElement)': not all code paths return a value

and happy new year to you to thanks for the patient help

You just moved the whole code correct? You need to find a way to assign the variable. Looks to me like you can:

private List<FaultTree> GetFaultTrees(XElement element)
        {
            IEnumerable<FaultTree> x = (from faultTree in element.Elements("FaultTrees")
                        select new FaultTree()
                        {
                            Name = faultTree.Attribute("Events").Value,
                            SubCategories = this.GetFaultTrees(faultTree)
                        });

            return x.ToList<FaultTree>();
        }

Try using that. I have no idea if it will work because I don't have your XML document.

If it still returns with object reference error then it has to be the following line is returning a value of null from faultTree.Attribute().Value to the Name variable.

Name = faultTree.Attribute("Events").Value

You can set up null handling on your application; using an if statement saying that if the value returned is null, don't return the value, return a default value (empty fault tree).

You just moved the whole code correct? You need to find a way to assign the variable. Looks to me like you can:

private List<FaultTree> GetFaultTrees(XElement element)
        {
            IEnumerable<FaultTree> x = (from faultTree in element.Elements("FaultTrees")
                        select new FaultTree()
                        {
                            Name = faultTree.Attribute("Events").Value,
                            SubCategories = this.GetFaultTrees(faultTree)
                        });

            return x.ToList<FaultTree>();
        }

Try using that. I have no idea if it will work because I don't have your XML document.

this was unsuccessful so I will now look at Null handling, like you suggest and see what I can come up with

Basically you just want to prevent values from returning null (particularly with arrays and lists) by setting up a default value; the concept is quite simple. Say you're declaring an integer variable.

int iMyInteger;

Most of us automatically assign a value to this integer because we need a specific one. However by setting it to zero it's called a default value. Zero is the default value for an integer. So instead of just declaring my variable I will assign the value of zero to it at declaration.

int iMyInteger = 0;

This is especially important with arrays, because using arrays before they are initialized will throw an Array Index Out Of Bounds exception or Object Reference Not Set To Instance Of An Object and stops the program. So with arrays that's why unless we're assigning the values somewhere else in multiple spots throughout the source code we assign it at declaration.

int[, , ,] imaMyMultiDimensionalIntegerArray = new int[1, 2, 3, 4];

// Instead of:
int[, , ,] imaMyMultiDimensionalIntegerArray;

Hope this helps. :)
Jamie

That's because you haven't provided for the return of the function in both the try and catch blocks. If a function returns a value or object all code paths must ensure something is returned. Your catch block is probably the culprit.

EDIT: Oops, didn't see there was a page 2... I'm a bit late with this post

That's because you haven't provided for the return of the function in both the try and catch blocks. If a function returns a value or object all code paths must ensure something is returned. Your catch block is probably the culprit.

EDIT: Oops, didn't see there was a page 2... I'm a bit late with this post

LOL Yeah, I'm saying set a default value to ensure a safe return. I'm also thinking it's within the XML document that the value is null anyways. Because he's drawing a value from there and storing it into a variable, that value is returning null. Strings by default are empty not null as far as I know. I still declare them to String.Empty anyways to be safe.

Basically you just want to prevent values from returning null (particularly with arrays and lists) by setting up a default value; the concept is quite simple. Say you're declaring an integer variable.

int iMyInteger;

Most of us automatically assign a value to this integer because we need a specific one. However by setting it to zero it's called a default value. Zero is the default value for an integer. So instead of just declaring my variable I will assign the value of zero to it at declaration.

int iMyInteger = 0;

This is especially important with arrays, because using arrays before they are initialized will throw an Array Index Out Of Bounds exception or Object Reference Not Set To Instance Of An Object and stops the program. So with arrays that's why unless we're assigning the values somewhere else in multiple spots throughout the source code we assign it at declaration.

int[, , ,] imaMyMultiDimensionalIntegerArray = new int[1, 2, 3, 4];

// Instead of:
int[, , ,] imaMyMultiDimensionalIntegerArray;

Hope this helps. :)
Jamie

whilst I understand what you are saying I'm not entirely sure what to default....is it Name?

Well, name seems to just be a string so there's no reason to default it's value. You want to make sure your fault tree object doesn't return a null value to the method. So you have to set up a prevention. Here's an example with a method that returns a color.

public Color GetColor(Color tc)
{
Color x = Color.White;

if (tc == null)
x = Color.White;

else
x = tc;

return x;
}

Something of that nature. As you can see, if tc is null we're returning a default value of white. You can also do this with fewer lines by assigning the value to the parameter object.

public Color GetColor(Color tc)
{
if (tc == null)
tc = Color.White;

return tc;
}

;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.