Viks
Viks

Reputation: 413

Object reference not set to an instance of object error

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?

Upvotes: 2

Views: 966

Answers (4)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93494

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.

Upvotes: 5

JaredPar
JaredPar

Reputation: 755587

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

Upvotes: 0

Andy
Andy

Reputation: 30428

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.

Upvotes: 0

Otávio Décio
Otávio Décio

Reputation: 74320

All these could return null:

xe.Element("Product") 

xe.Element("Product") 
.Elements() 

Upvotes: 0

Related Questions