Null Reference Exception for Class Lists

When you create BookList, you haven’t actually initialized the list that is its member. You can do this by changing your initialization to:

BookList myBookList = new BookList() {bookList = new List<Book>()};

Or by writing a constructor for the BookList class which initializes the list; which would look like this:

class BookList
{
    public List<Book> bookList { get; set; }

    public BookList(){ //New constructor
        bookList = new List<Book>();
    }
}

The reason you get this error is that while you’ve created an instance of BookList, you haven’t actually make sure that the BookList‘s inner booklist property is initialized. It’s like if you tried to do this:

List<string> newList;
newList.Add("foo");

That wouldn’t work because you’ve only declared the newList, not initialized it.

Leave a Comment