tags:

views:

555

answers:

4

I get this error "Object reference not set to an instance of object error" when I execute this piece of code

xe.Element("Product") // Select the Product desc="household" element  
.Elements() 
.Select(element => 
new { Name=(string) element.Attribute("desc"),                           
Count=element.Elements().Count() });

What could be the reason?

+4  A: 

Try breaking it apart.

var e = xe.Element("Product");
var elements = e.Elements();
elelements.Select(element =>...

etc.. Find the smallest unit of code that causes the error. That will help isolate things. Also, use the debugger watch windows. Look for nulls.

Mystere Man
A: 

All these could return null:

xe.Element("Product") 

xe.Element("Product") 
.Elements()
Otávio Décio
A: 

One of the references you're using is null. Verify that xe is non-null, and that there is a Product tag, that has elements. Also, if the selected tag doesn't have any child elements, then the setting of the Count property on the anonymous type could generate this error, as well.

If nothing else, you can try to split this into multiple lines to see which line throws the exception. That should help you to narrow down the problem.

Andy
A: 

Have you checked to verify that xe is not "null". That is the most likely cause of your problem.

JaredPar