Null Reference Exception for Class Lists

I am new to programming and am running into an issue when creating a class with a list property of another class and then accessing it in main. I am getting the exception "Object reference not set to an instance of an object" after trying to Add an item to the list I get this error during runtime. I do understand that the List<> reference is null but am trying to understand why it is null and how to get around it. My code will function properly if I just create the List in main but I would like to have it as a class in the future. Like I said I am new to programming OOP and trying to get some information regarding why this is happening. I apologize if this is a repeat question. My code snippet is below:

static void Main(string[] args)
    {
        BookList myBookList = new BookList();

        myBookList.bookList.Add(new Book("The Giver", "Lois Lowry", "Houghton Mifflin"));
        myBookList.bookList.Add(new Book("Telling Lies", "Paul Ekman", "Norton & Company"));
    }


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

class Book
{
    public Book(string title, string author, string publisher)
    {
        Title = title;
        Author = author;
        Publisher = publisher;
    }

    public string Title { get; set; }
    public string Author { get; set; }
    public string Publisher { get; set; }        
}

Thank you, I appreciate all the help!


Solution 1:

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.