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;
}
}
}