views:

129

answers:

2

According to my LINQ book, this slightly altered example should work.

Why does it tell me "Object reference not set to an instance of an object"?

using System;
using System.Xml.Linq;

namespace TestNoAttribute
{
    class Program
    {
        static void Main(string[] args)
        {

            XDocument xdoc = new XDocument(
                new XElement("employee",
                    new XAttribute("id", "23"),
                    new XElement("firstName", new XAttribute("display", "true"), "Jim"),
                    new XElement("lastName", new XAttribute("display", "false"), "Smith")));

            XElement element = xdoc.Element("firstName");
            XAttribute attribute = element.Attribute("display"); //error

            Console.WriteLine(xdoc);

            Console.ReadLine();

        }
    }
}

Partial Answer:

I figured out if I change XDocument to XElement, then it works. Could anyone explain why?

+4  A: 

You are accessing a child element of xdoc that doesn't exist. Try one level down:

XElement element = xdoc.Element("employee").Element("firstName");

or

XElement element = xdoc.Descendants("firstName").FirstOrDefault();
bruno conde
Agreed, but why does it throw the exception on the next line of code, rather than this one?
Robert Harvey
Because in the next line of code element was null. If the element doesn't exist no exception is thrown (at xdoc.Element("firstName")).
bruno conde
OK I get it....
Robert Harvey
+2  A: 

See this on MSDN as to why. It explicitly explains their 'idiom' on why they felt returning a null element when the name is not found was beneficial.

Marc