0

This is NOT a question about the NullReferenceException. It is a question about why the statement shown would be throwing one and what is wrong with it.

I am attempting to parse a small XML document using Linq.Xml and am getting a Null Reference exception when attempting to create a list of objects from a Linq query

            _columnDefs = (from def in fileDef.Descendants("columndef")
                       select new ColumnDef ()
                        { 
                            Name = def.Attribute("Name").Value,
                            Type = def.Attribute("Type").Value,
                            Required = bool.Parse(def.Attribute("Required").Value),
                            Default = def.Attribute("Default").Value
                        }).ToList<ColumnDef>();

The code here fails with a NullReferenceException as seen here

enter image description here

I'm having trouble trying to figure out if the new ColumDef object is the issue or something else. If it is the new ColumnDef then why is the "new" operator not creating an instance of the object?

_columnDefs is defined as _columnDefs = new List<ColumnDef>();

dscarr
  • 1,770
  • 1
  • 16
  • 21
  • 1
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Jason P Sep 30 '15 at 15:31
  • Every `columndef`'s node contains the attributes `Name`,`Type`,`Required`,`Default`? – Matteo Umili Sep 30 '15 at 15:35
  • @coderoipo - They do not. I was under the impression that it would fill the string variable ('Default' in this case is an optional Attribute) with null and leave it at that. What would be the best way to solve this issue? Can I actually write a conditional statement inside the Linq statement? – dscarr Sep 30 '15 at 15:38

1 Answers1

1

Your debugger view shows that the current item has no Default attribute. You can use default = (string)def.Attribute("Default") to have the property set to null if the attribute does not exist.

Martin Honnen
  • 138,662
  • 6
  • 76
  • 93
  • If he is using C# 6 he could also achieve the same thing (and maybe give more of a hint to the reader that he knows this value may be null) by using the null propagation operator - def.Attribute("Default")?.Value – TVOHM Sep 30 '15 at 15:46
  • Thanks to @coderoipo, Martin and TVOHM for their responses. coderoipo got me started in the right direction for searching for an answer and Martin and TVOHM pointed out what I clearly missed. Thanks again! – dscarr Sep 30 '15 at 15:54