[RESOLVED] NullReferenceException when adding to list
I thought that I knew how to handle those NullReferenceExceptions...but I simply don't know what to do with this one :ehh:
Part of my Code:
Code:
public class Chapter
{
public string Name;
public TimeSpan Time;
}
public class ChapterSet
{
public List<Chapter> Chapters;
}
public ArrayList GrabChapters(string searchString)
{
...(Unimportant code)...
foreach (XmlNode node in NodeList)
{
ChapterSet chapterSet = new ChapterSet();
XmlNodeList chapters = node.ChildNodes;
foreach (XmlNode chapter in chapters)
{
Chapter pChapter = new Chapter();
pChapter.Name = chapter.Attributes["name"].Value;
pChapter.Time = TimeSpan.Parse(chapter.Attributes["time"].Value);
chapterSet.Chapters.Add(pChapter);
}
Results.Add(chapterSet);
}
return Results;
}
Anyone that can give a good explanation why this happens? (On the red line)
Re: NullReferenceException when adding to list
The explanation is quite simple: chapterSet.Chapters is null because you have never assigned anything to it. Here's your ChapterSet class:
Code:
public class ChapterSet
{
public List<Chapter> Chapters;
}
It declares a public field named Chapters but it never assigns anything to it internally, so if you expect the field to have a value, you must assign something to it externally. Here's the code that creates and uses a ChapterSet object:
Code:
ChapterSet chapterSet = new ChapterSet();
XmlNodeList chapters = node.ChildNodes;
foreach (XmlNode chapter in chapters)
{
Chapter pChapter = new Chapter();
pChapter.Name = chapter.Attributes["name"].Value;
pChapter.Time = TimeSpan.Parse(chapter.Attributes["time"].Value);
chapterSet.Chapters.Add(pChapter);
The first line creates the ChapterSet object and the last line tries to use the value of its Chapters field, but nowhere in between do you actually assign anything to that Chapters field. To use your ChapterSet class as is you would have to do this:
Code:
chapterSet.Chapters = new List<Chapter>();
The more sensible approach would be to have the ChapterSet class create the List itself. The most correct approach would be to use a private field and a public read-only property:
Code:
public class ChapterSet
{
private List<Chapter> _chapters = new List<Chapter>();
public List<Chapter> Chapters { get { return _chapters; } }
}
If appropriate, you might add lazy loading:
Code:
public class ChapterSet
{
private List<Chapter> _chapters;
public List<Chapter> Chapters
{
get
{
if (_chapters == null)
{
_chapters = new List<Chapter>();
}
return _chapters;
}
}
}
Re: NullReferenceException when adding to list
Really good explanation, now I understand! Wish I could give you +rep
"I wrote I was going to create a bag that I could put things in, then I tried putting the things in the bag before it was created, and that simply doesn't work" ;)